使用Spring JdbcTemplate选择数据的最佳实践

问题描述 投票:21回答:4

我想知道从表中选择记录的最佳做法是什么。我在下面提到了两种方法,我想知道哪种方法是使用Spring JdbcTemplate从表中选择数据的最佳方法。

第一个例子

try {
    String sql = "SELECT id FROM tableName WHERE column_name = '" + coulmn value + "'";

    long id = jdbcTemplate.queryForObject(sql, Long.class);
} catch (Exception e) {
    if (log.isDebugEnabled()) {
        log.debug(e);
    }
}

这会引发以下异常:

预计1实际0喜欢

当表不包含任何数据时。我的朋友告诉这不是选择数据的最佳做法。他建议下面提到的代码是选择数据的唯一最佳实践。

第二个例子

try {
    String countQuery = "SELECT COUNT(id) FROM tableName";

    int count = jdbcTemplate.queryForInt(countQuery);
    if (count > 0) {
        String sql = "SELECT id FROM tableName WHERE column_name = '" + coulmn value + "'";

        long id = jdbcTemplate.queryForObject(sql, Long.class);
    }
} catch (Exception e) {
    if (log.isDebugEnabled()) {
        log.debug(e);
    }
}

我渴望知道正确的一个或任何其他最佳实践。

java spring jdbctemplate
4个回答
21
投票

绝对第一种方式是最佳实践,因为在第二种方式中,您只能在数据库中击中两次,实际上只能击中它一次。这可能会导致性能问题。

你需要做的是捕获异常EmptyResultDataAccessException然后返回null。 Spring JDBC模板如果在数据库中找不到数据,则会抛出EmptyResultDataAccessException异常。

您的代码应如下所示。

try {
     sql = "SELECT id FROM tableNmae WHERE column_name ='"+ coulmn value+ "'";
     id= jdbcTemplate.queryForObject(sql, Long.class);
} 
catch (EmptyResultDataAccessException e) {
   if(log.isDebugEnabled()){
       log.debug(e);
   }
   return null
}

3
投票

更好的方法在查询中使用ifNull,所以如果有null那么你得到0 Eg.-

sql = "SELECT ifNull(id,0) FROM tableName WHERE column_name ='"+ coulmn value+ "'";

使用这种方式,您可以获得默认值0,否则您的Id


2
投票

我正面临类似的情况,并在使用ResultSetExtractor而不是RowMapper时找到了更清晰的解决方案

jdbcTemplate.query(DBConstants.GET_VENDOR_DOCUMENT, new Object[]{vendorid}, rs -> {

            if(rs.next()){
                DocumentPojo vendorDoc = new DocumentPojo();
                vendorDoc.setRegDocument(rs.getString("registrationdoc"));
                vendorDoc.setMsmeLetter(rs.getString("msmeletter"));
                vendorDoc.setProprietorshipDocument(rs.getString("propertiershipformat"));
                vendorDoc.setNeftDocument(rs.getString("neftdoc"));
                vendorDoc.setPanCardDocument(rs.getString("pancard"));
                vendorDoc.setCancelledChequeDoc(rs.getString("cheque"));
                return vendorDoc;
            }
            else {
                return null;
            }

    });

如果没有从数据库中找到结果,我为结果集设置了if条件并返回null引用。所以,我不需要尝试捕获代码并将两个查询传递给数据库。

ResultSetExtractor(在这种情况下)的主要优点是使用ResultsetExtractor,您需要自己遍历结果集,比如while循环。

更多积分可以在这里找到here


0
投票

这是queryForObject方法的源代码

@Nullable
public <T> T queryForObject(String sql, RowMapper<T> rowMapper) throws 
DataAccessException {
    List<T> results = this.query(sql, rowMapper);
    return DataAccessUtils.nullableSingleResult(results);
}

DataAccessUtils.nullableSingleResult

    @Nullable
public static <T> T nullableSingleResult(@Nullable Collection<T> results) throws IncorrectResultSizeDataAccessException {
    if (CollectionUtils.isEmpty(results)) {
        throw new EmptyResultDataAccessException(1);
    } else if (results.size() > 1) {
        throw new IncorrectResultSizeDataAccessException(1, results.size());
    } else {
        return results.iterator().next();
    }
}

不知道为什么他们在空集合上抛出异常,可能这只是上面方法的复制粘贴

    public static <T> T requiredSingleResult(@Nullable Collection<T> results) throws IncorrectResultSizeDataAccessException {
    if (CollectionUtils.isEmpty(results)) {
        throw new EmptyResultDataAccessException(1);
    } else if (results.size() > 1) {
        throw new IncorrectResultSizeDataAccessException(1, results.size());
    } else {
        return results.iterator().next();
    }
}

比他们应该使用的方法还要多一步

    @Nullable
public static <T> T singleResult(@Nullable Collection<T> results) throws IncorrectResultSizeDataAccessException {
    if (CollectionUtils.isEmpty(results)) {
        return null;
    } else if (results.size() > 1) {
        throw new IncorrectResultSizeDataAccessException(1, results.size());
    } else {
        return results.iterator().next();
    }
}

现在解决方案帮助我:扩展JdbcTemlate类(您可以使用注入的DataSource构造它)并覆盖queryForObject方法:

    @Nullable
public <T> T queryForObject(String sql, RowMapper<T> rowMapper) throws DataAccessException {
    List<T> results = this.query(sql, rowMapper);
    return DataAccessUtils.singleResult(results);
}

现在使用您的实现不要忘记检查它是否适用于Spring版本更新(非常不可能恕我直言)

© www.soinside.com 2019 - 2024. All rights reserved.