سؤال

I would like to return a boolean value using in this method:

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;
}

Kindly help. Thanks.

هل كانت مفيدة؟

المحلول

If you want to write a method that checks that a record exists in the database you can use the following code:

Integer cnt = jdbcTemplate.queryForObject(
    "SELECT count(*) FROM customer_pool WHERE id = ? AND level = 13)", Integer.class, id);
return cnt != null && cnt > 0

نصائح أخرى

Counting rows in SQL just in order to get simple information about non-emptiness of result may be unnecessary overkill, you want just ask result set for first row and finish. For simple queries by primary key or other index the performance might be similar, however, for complex queries, or full table scan queries it might be slow. In Spring I prefer simple utility method

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" for more info.)

What about

// 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;
}

Case 1: In case you are returning boolean: Just check the size of sizeResult List, if the size is greater than 0 return true else return false.

Case 2: If you are returning boolean list then return type must be a boolean List.You must write the method as:

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;

}

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top