Spring JDBC Framework simplifies the use of JDBC and helps to avoid common errors.
The following example shows querying for an object using JdbcTemplate class.
/**
* 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 = 1;
User user = template.queryForObject(
"select * from USER where ID = ?", new RowMapper<User>() {
@Override public User mapRow(ResultSet rs, int rowNum) throws SQLException {
return new User(
rs.getInt("ID"),
rs.getString("NAME"),
rs.getInt("age"),
rs.getLong("SALARY")
);
}