Spring JDBC Framework simplifies the use of JDBC and helps to avoid common errors.
The following example shows querying records using NamedParameterJdbcTemplate
and BeanPropertySqlParameterSource classes.
It extracts the specified named parameters from the given bean 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);
Pager pager = new Pager(1, 3);
SqlParameterSource namedParameters = new BeanPropertySqlParameterSource(pager);
List<Map<String, Object>> rows = template.queryForList(
"select ID, NAME, AGE from USER where ID >= :startId and ID < :endId",
namedParameters);
System.out.println(rows);
}
}
class Pager { private int startId; private int endId;
public Pager(int startId, int endId) { super(); this.startId = startId; this.endId = endId;
} public int getStartId() { return startId;
} public void setStartId(int startId) { this.startId = startId;
} public int getEndId() { return endId;
} public void setEndId(int endId) { this.endId = endId;
}
}