Spring JDBC
- SQL를 쉽게 날릴수 있도록 만들어진 library
- RowMapper 인터페이스를 통해 데이터맵핑을 할수 있다.
- JdbcTemplate, NamedParameterTemplate
- Datasource가 필요하다.
- Spring Data Jpa 등의 ORM을 사용할때, DB의 Index Hints 기능을 활용하지 못하는데 Spring JDBC를 직접 Native Query를 작성함으로써 해결을 할수있다.
JdbcTemplate
int rowCount = this.jdbcTemplate.queryForObject("select count(*) from t_actor", Integer.class);
int countOfActorsNamedJoe = this.jdbcTemplate.queryForObject(
"select count(*) from t_actor where first_name = ?", Integer.class, "Joe");
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;
}
});
NamedParameterJdbcTemplate
// some JDBC-backed DAO class...
private NamedParameterJdbcTemplate namedParameterJdbcTemplate;
public void setDataSource(DataSource dataSource) {
this.namedParameterJdbcTemplate = new NamedParameterJdbcTemplate(dataSource);
}
public int countOfActorsByFirstName(String firstName) {
String sql = "select count(*) from T_ACTOR where first_name = :first_name";
SqlParameterSource namedParameters = new MapSqlParameterSource("first_name", firstName);
return this.namedParameterJdbcTemplate.queryForObject(sql, namedParameters, Integer.class);
}
Log 설정
log4j.logger.org.springframework.jdbc.core = TRACE
- 쿼리가 어떤 파라미터와 함께 처리가 되는지를 확인하기 위해서는 `org.springframework.jdbc.core`에 해당하는 로그레벨의 조절을 하면 된다.
Reference
'Programing > Spring Framework' 카테고리의 다른 글
Spring Bean Life Cycle (0) | 2018.09.21 |
---|---|
Spring @Transactional Propagation (0) | 2018.09.10 |
Spring Constructor Dependency Injection (0) | 2018.09.06 |
Attribute Converter를 이용한 커스텀 컬럼 사용하기 (0) | 2017.08.06 |
@Value 어노테이션 활용 (0) | 2017.06.28 |