Spring JDBC Framework simplifies the use of JDBC and helps to avoid common errors.
The following example shows querying records using NamedParameterJdbcTemplate
and MapSqlParameterSource classes.
It extracts the specified named parameters from the given map source for query execution.
/**
* Initialize context and get the NamedParameterJdbcTemplate
*/
ApplicationContext appContext = new ClassPathXmlApplicationContext("applicationContext.xml");
DataSource dataSource = (DataSource) appContext.getBean("dataSource");
NamedParameterJdbcTemplate template = new NamedParameterJdbcTemplate(dataSource);
MapSqlParameterSource namedParameters = new MapSqlParameterSource("start_id", 1);
namedParameters.addValue("end_id", 3);
List<Map<String, Object>> rows = template.queryForList(
"select ID, NAME, AGE from USER where ID >= :start_id and ID < :end_id",
namedParameters);