JdbcTemplate "queryForObject" and "query" is deprecated in Spring. What should it be replaced by?

Viewed 29220

Query for object,

Student student = return jdbcTemplate.queryForObject("select * from student_id = ?", new Object[] { studentId }, studentRowMapper);

For query,

List<Student> students = return jdbcTemplate.query("select * from class_room_id = ?", new Object[] { classRoomId }, studentRowMapper);

Both jdbcTemplate.queryForObject and jdbcTemplate.query are deprecated in spring boot 2.4.X above

2 Answers

As explained in the javadoc of the class as well as in the upgrade/migration guide it explains that you should use the varargs method.

jdbcTemplate.queryForObject("select * from student_id = ?", studentRowMapper, studentId);

and

List<Student> students = return jdbcTemplate.query("select * from class_room_id = ?", studentRowMapper, classRoomId);

You can just change the order of the array Object[ ] and the mapper. This syntax is supported in the current version. So your code would be:

Student student = return jdbcTemplate.queryForObject("select * from student_id = ?", 
studentRowMapper, new Object[] { studentId });

and

List<Student> students = return jdbcTemplate.query("select * from class_room_id = ?", 
studentRowMapper, new Object[] { classRoomId });

You can see the doc of this method here.

Related