25

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

kohane15
  • 809
  • 12
  • 16
Thirumal
  • 8,280
  • 11
  • 53
  • 103
  • The one with a varargs argument instead of the `Object[]`. This is also explained in the `@depracted` documentation. See https://docs.spring.io/spring-framework/docs/current/javadoc-api/org/springframework/jdbc/core/JdbcOperations.html#query-java.lang.String-java.lang.Object:A-org.springframework.jdbc.core.ResultSetExtractor- as well as explained in the upgrade documentation https://github.com/spring-projects/spring-framework/wiki/Upgrading-to-Spring-Framework-5.x#data-access-and-transactions – M. Deinum Dec 15 '20 at 06:39

2 Answers2

46

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);
M. Deinum
  • 115,695
  • 22
  • 220
  • 224
17

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.

JoM
  • 236
  • 2
  • 4
  • 4
    You can simplify this further by removing the `new Object[] { ... }` around the parameter, as it is a varargs parameter. – Mark Rotteveel Sep 02 '22 at 12:54
  • The Object[] is deprecated now, developers should go ahead with the varargs approach, see https://docs.spring.io/spring-framework/docs/current/javadoc-api/org/springframework/jdbc/core/JdbcOperations.html#query(java.lang.String,java.lang.Object%5B%5D,org.springframework.jdbc.core.RowMapper) – patrick.holzer May 08 '23 at 10:10