Jdbc Template

어겐어갠·2022년 4월 13일
0

Jdbc Template

  • 스프링이 제공하는 Jdbc의 중복되는 코드를 제거해주는 API
  • 여기서 중복되는 부분이란 Connection과 PreparedStatement 객체 생성과 ResultSet, PreparedStatement, Connection 타입 객체의 종료를 뜻한다.

Jdbc Template의 생성

  • DataSource가 필요하다.
  • setter로도 DataSource를 주입해줄 수 있지만, 보통은 생성자를 사용하는 듯 싶다.
public class MemberDao {

	private JdbcTemplate jdbcTemplate;

	public MemberDao(DataSource dataSource) {
		this.jdbcTemplate = new JdbcTemplate(dataSource);
	}
}

Insert, Update, Delete 문 = update

int update = jdbcTemplate.update("update customers set name = ?, email = ?, last_login_at = ? where customer_id = UUID_TO_BIN(?)",
                customer.getName(),
                customer.getEmail(),
                customer.getLastLoginAt() != null ? Timestamp.valueOf(customer.getLastLoginAt()) : null,
                customer.getCustomerId().toString().getBytes());
=======================================================================================================================================
jdbcTemplate.update("delete from customers");

결과가 1행일 경우(find, count 등) = queryForObject

return Optional.of(jdbcTemplate.queryForObject("select * from customers where customer_id  = UUId_TO_BIN(?)", customerRowMapper(), customerId.toString().getBytes()));
================================================================================================================================================================
return jdbcTemplate.queryForObject("select count(*) from customers", Integer.class);

위에서 사용된 RowMapper

RowMapper의 mapRow() 메서드는 SQL 실행 결과로 구한 ResultSet에서 한 행의 데이터를 읽어와 자바 객체로 변환하는 매퍼 기능을 구현합니다.

    private static final RowMapper<Customer> customerRowMapper() {
        return (resultSet, i) -> {
            String customerName = resultSet.getString("name");
            UUID customerId = toUUID(resultSet.getBytes("customer_id"));
            String email = resultSet.getString("email");
            LocalDateTime createdAt = resultSet.getTimestamp("created_at").toLocalDateTime();
            LocalDateTime lastLoginAt = resultSet.getTimestamp("last_login_at") != null ?
                    resultSet.getTimestamp("last_login_at").toLocalDateTime() : null;
            return new Customer(customerId, customerName, email, lastLoginAt, createdAt);
        };
    }

https://jaehoney.tistory.com/34
https://velog.io/@albaneo0724/Spring-JDBC-Template-%EC%82%AC%EC%9A%A9%ED%95%B4-DB-%EC%BB%A8%ED%8A%B8%EB%A1%A4-%ED%95%98%EA%B8%B0

profile
음그래

0개의 댓글