我想在此方法中返回一个布尔值:
public Boolean isSizeOk(String transactionId){
String sqlQuery = "SELECT true FROM customer_pool WHERE id = "+ transactionID + " AND level = 13)";
//The next line is the problem.
//If I am returning a Boolean List, I can write
List <Boolean> sizeResult = jdbcTemplate.queryForList(sqlQuery, Boolean.class, transactionId);
//But since I only want a boolean value, what will the statement be?
Boolean sizeResult = jdbcTemplate......?
return sizeResult;
}
请帮助。感谢。
答案 0 :(得分:21)
如果要编写检查数据库中是否存在记录的方法,可以使用以下代码:
Integer cnt = jdbcTemplate.queryForObject(
"SELECT count(*) FROM customer_pool WHERE id = ? AND level = 13)", Integer.class, id);
return cnt != null && cnt > 0
答案 1 :(得分:7)
在SQL中计算行只是为了获得有关结果非空的简单信息可能是不必要的过度杀戮,你只需要在第一行询问结果集并完成。对于主键或其他索引的简单查询,性能可能类似,但是,对于复杂查询或全表扫描查询,它可能很慢。在Spring中,我更喜欢简单的实用方法
public boolean exists(String sql, Object... args) {
boolean result = query(sql, args, new ResultSetExtractor<Boolean>() {
@Override
public Boolean extractData(ResultSet rs) throws SQLException,DataAccessException {
boolean result = rs.next();
return result;
}
});
return result;
}
(Google“sql exists vs count”了解更多信息。)
答案 2 :(得分:4)
怎么样?
// Change query accordingly
String query = "SELECT 1 FROM " + tableName + " WHERE " + idColumnName + " = ? LIMIT 1";
try {
jdbcTemplate.queryForObject(query, new Object[]{id}, Long.class);
return true;
} catch (EmptyResultDataAccessException e) {
return false;
}
答案 3 :(得分:0)
案例1:如果你要返回布尔值: 只需检查 sizeResult 列表的大小,如果大小大于 0 返回 true ,则返回假强>
案例2:如果要返回布尔列表,则返回类型必须是布尔列表。您必须 将方法写为:
public List<Boolean> isSizeOk(String transactionId, int sizeLimit){
String sqlQuery = "SELECT true FROM customer_pool WHERE id = ? AND level = 13)";
List <Boolean> sizeResult = jdbcTemplate.queryForList(sqlQuery, Boolean.class, transactionId);
Boolean sizeResult = jdbcTemplate......?
return sizeResult;
}