Home > Back-end >  Spring jdbcTemplate retrieve numeric values from query
Spring jdbcTemplate retrieve numeric values from query

Time:02-11

I have this query for my jdbcTemplate and I wanna get just the long value from the database, what should be fixed here?

String query = "SELECT size from users where name = ? AND type = ?";
long size = jdbcTemplate.query(query, new Object[]{id, type}, (rs, rowNum) -> 
rs.getLong("size"));

CodePudding user response:

long size = jdbcTemplate.queryForObject(query, Long.class);

CodePudding user response:

If you look at the query javadocs in JdbcOperations it states:

Deprecated. as of 5.3, in favor of query(String, RowMapper, Object...)

So you can use it like this:

List<Long> sizeResults = jdbcTemplate.query(query, (rs, rowNum) ->
        rs.getLong("size"), id, type);
if (sizeResults.isEmpty()){
    System.out.println("Result not found!");
} else {
    System.out.println("Result found!");
}

Note: queryForObject throws EmptyResultDataAccessException for empty results. Often it is not desired behavior.

  • Related