Spring JDBC Framework simplifies the use of JDBC and helps to avoid common errors.
The following example shows using BeanPropertyRowMapper class.
It maps each row of the resultset with a new instance of target class.
The target class should have a no-argument default constructor.
It maps the column names from resultset to properties of target class using public setter methods.
If column name doesn't match with property name, we need to provide a column alias
matching the property name.
/**
* Initialize context and get the JdbcTemplate
*/
ApplicationContext appContext = new ClassPathXmlApplicationContext("applicationContext.xml");
DataSource dataSource = (DataSource) appContext.getBean("dataSource");
JdbcTemplate template = new JdbcTemplate(dataSource);
int userId = 3;
User user = template.queryForObject(
"select ID as userId, NAME as userName, AGE, SALARY " +
"from USER where ID = ?", new BeanPropertyRowMapper<User>(User.class), userId);