Monday, February 22, 2010

Using Spring JdbcTemplate to queryForObject example

I needed to make a quick query to check some data before inserting a new record. The queryForObject allows you to create an inner RowMapper class to handle the ResultSet…in this case, I needed to return two integers so I mapped the results to an integer array with two elements:


JdbcTemplate springTemplate = new JdbcTemplate(this.currDs);
int[] user = springTemplate.queryForObject(
"select UserID, count(*) from t_actor where orgID = ?",
new Object[]{new Long(1212)},
new RowMapper<int[]>() {

public int[] mapRow(ResultSet rs, int rowNum) throws SQLException {
int[] user = new int[2];
user[0] = rs.getInt(0);
user[1] = rs.getInt(1);
return user;
}
});

No comments: