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

2

27

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

Kenwrick answered 15/12, 2020 at 6:27 Comment(1)
The one with a varargs argument instead of the Object[]. This is also explained in the @depracted documentation. See docs.spring.io/spring-framework/docs/current/javadoc-api/org/… as well as explained in the upgrade documentation github.com/spring-projects/spring-framework/wiki/…Auriferous
A
50

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);
Auriferous answered 15/12, 2020 at 6:42 Comment(0)
A
19

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.

Ambi answered 21/4, 2021 at 10:28 Comment(2)
You can simplify this further by removing the new Object[] { ... } around the parameter, as it is a varargs parameter.Extracellular
The Object[] is deprecated now, developers should go ahead with the varargs approach, see docs.spring.io/spring-framework/docs/current/javadoc-api/org/…Quack

© 2022 - 2024 — McMap. All rights reserved.