- JDBC 프로그래밍을 보면 반복되는 개발 요소가 있다.
- 이러한 JDBC의 모든 저수준 세부사항을 스프링 프레임워크가 처리해준다.
열의 수 구하기
int rowCount = this.jdbcTemplate.queryForInt("select count(*) from t_actor");
변수 바인딩 사용하기
int countOfActorsNamedJoe = this.jdbcTemplate.queryForInt("select count(*) from t_actor where first_name = ?", "Joe");
String값으로 결과 받기
String lastName = this.jdbcTemplate.queryForObject("select last_name from t_actor where id = ?", new Object[] {1212L}, String.class);
한 건 조회하기
Actor actor = this.jdbcTemplate.queryForObject(
"SELECT first_name, last_name FROM t_actor where id = ?",
new Object[] {1212L},
new RowMapper<Actor> {
public Actor mapRow(ResultSet rs, int rowNum) throws SQLException {
Actor actor = new Actor();
actor.setFirstName(rs.getString("first_name"));
actor.setLastName(rs.getString("last_name"));
return actor;
}
});
List<Actor> actors = this.jdbcTemplate.query(
"select first_name, last_name from t_actor",
new RowMapper<Actor>() {
public Actor mapRow(ResultSet rs, int rowNum) throws SQLException {
Actor actor = new Actor();
actor.setFirstName(rs.getString("first_name"));
actor.setLastName(rs.getString("last_name"));
return actor;
}
});
public List<Actor> findAllActors() {
return this.jdbcTemplate.query( "select first_name, last_name from t_actor", new ActorMapper());
}
private static final class ActorMapper implements RowMapper<Actor> {
public Actor mapRow(ResultSet rs, int rowNum) throws SQLException {
Actor actor = new Actor();
actor.setFirstName(rs.getString("first_name"));
actor.setLastName(rs.getString("last_name"));
return actor;
}
}
this.jdbcTemplate.update("insert into t_actor (first_name, last_name) values (?, ?)", "Leonor", "Watling");
this.jdbcTemplate.update("update t_actor set = ? where id = ?", "Banjo", 5276L);
this.jdbcTemplate.update("delete from actor where id = ?", Long.valueOf(actorId));