JdbcTemplate deprecated method queryForLong() and queryForInt() in Spring 4 and in spring 3.2.x


 sunflower   Since the jdbcTemplate.queryForInt() and jdbcTemplate.queryForLong() are deprecated in new version of spring(i think,After3.2.x,they are deprecated).We will have to use  jdbcTemplate.queryForObject() for the purpose .We should take care following coding practice otherwise  unwanted exceptions can come.

1.When we will use jdbcTemplate.queryForInt() for getting some int value in a query like:

Existing use of queryForInt() for getting int value:

public int getLineNumber(String orderId, String orderType) {
String sql = "SELECT MAX(order_line_no) FROM ORDER WHERE order_id = ? and order_type = ?";
int value = jdbcTemplate.queryForInt(sql, new Object[] {orderId, orderType});

return value
}

Or

public int getLineNumber(String orderId, String orderType) {
String sql = "SELECT MAX(order_line_no) FROM ORDER WHERE order_id = ? and order_type = ?";
return jdbcTemplate.queryForInt(sql, new Object[] {orderId, orderType});

}

 

Now because queryForInt() is deprecated,we will use queryForObject() for getting int value:

public int getLineNumber(String orderId, String orderType) {
String sql = "SELECT MAX(order_line_no) FROM ORDER WHERE order_id = ? and order_type = ?";
int value = jdbcTemplate.queryForObject(sql, new Object[] {orderId, orderType }, Integer.class);

return value
}

Or

public int getLineNumber(String orderId, String orderType) {
String sql = "SELECT MAX(order_line_no) FROM ORDER WHERE order_id = ? and order_type = ?";
return jdbcTemplate.queryForObject(sql, new Object[] {orderId, orderType }, Integer.class);

}

Now in the above code, if queryForObject return null value.It can not be assigned to primitive type int value .

So null pointer exception will come.To handle this , we should change our method like:

 

public int getLineNumber(String orderId, String orderType) {
String sql = "SELECT MAX(order_line_no) FROM ORDER WHERE order_id = ? and order_type = ?";
Integer value = jdbcTemplate.queryForObject(sql, new Object[] {orderId, orderType }, Integer.class);

return ((value == null) ? 0 : value.intValue());
}

This will ensure no exception if null is returned in the query.Similar changes can be applied to get an long value.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

w

Connecting to %s