Programing/Spring Framework

Spring JDBC

BUST 2018. 8. 23. 23:54

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