The JdbcTemplate class provides various methods to execute queries and manipulate the query results. Depending on the query and the expected result type, we can choose from the following three types of objects that can be returned from a JdbcTemplate query:
A. Generic Maps
This is true because the JdbcTemplate.queryForList method returns a List of Map objects, where each Map represents a row of the query result. The Map keys are the column names and the Map values are the column values1. For example:
List
B. Simple types (int, long, String, etc)
This is true because the JdbcTemplate.queryForObject method can return a single value of a simple type, such as int, long, String, etc. This method is useful for running queries that return a single row and a single column2. For example:
int count = jdbcTemplate.queryForObject(“SELECT COUNT(*) FROM EMPLOYEE”, Integer.class); System.out.println("Number of employees: " + count);
D. User defined types
This is true because the JdbcTemplate.query method can return a List of user defined types, such as custom classes or beans. This method takes a RowMapper as an argument, which is an interface that maps each row of the query result to an instance of the user defined type3. For example:
public class Employee { private String name; private int salary; // getters and setters }
public class EmployeeRowMapper implements RowMapper { @Override public Employee mapRow(ResultSet rs, int rowNum) throws SQLException { Employee employee = new Employee(); employee.setName(rs.getString(“NAME”)); employee.setSalary(rs.getInt(“SALARY”)); return employee; } }
List employees = jdbcTemplate.query(“SELECT * FROM EMPLOYEE”, new EmployeeRowMapper()); for (Employee employee : employees) { System.out.println(employee.getName() + " " + employee.getSalary()); }