Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

return a boolean - jdbcTemplate

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.

like image 531
bdfios Avatar asked Apr 04 '14 10:04

bdfios


3 Answers

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
like image 98
kostya Avatar answered Oct 01 '22 20:10

kostya


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.)

like image 45
Tomáš Záluský Avatar answered Oct 01 '22 18:10

Tomáš Záluský


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;
}
like image 36
Maxime Laval Avatar answered Oct 01 '22 19:10

Maxime Laval