private final JdbcTemplate jdbctemplate;
public NoticeRepository(JdbcTemplate jdbcTemplate) {
this.jdbcTemplate = jdbcTemplate;
}
jdbcTemplate.update() 메서드는 INSERT, UPDATE, DELETE 와 같이 생성, 수정, 삭제에 사용되고, 첫 번째 파라미터로 SQL을 받고 그 이후에는 ?에 들어갈 값을 받는다.
String sql = "INSERT INTO notices (username, contents) VALUES (?, ?)";
jdbcTemplate.update(sql, "EOMJI", "오늘 하루도 수고했어");
String sql = "UPDATE notices SET username = ? WHERE id = ?";
jdbcTemplate.update(sql, "EOMJI", 1);
String sql = "DELETE FROM notices WHERE id = ?";
jdbcTemplate.update(sql, 1);
String sql = "SELECT * FROM notices";
return jdbcTemplate.query(sql, new RowMapper<NoticeResponseDto>() {
@Override
public NoticeResponseDto mapRow(ResultSet rs, int rowNum) throws SQLException {
// SQL 의 결과로 받아온 Memo 데이터들을 MemoResponseDto 타입으로 변환해줄 메서드
Long id = rs.getLong("id");
String username = rs.getString("username");
String contents = rs.getString("contents");
return new NoticeResponseDto(id, username, contents);
}
});
SELECT의 경우 결과가 여러 줄로 넘어오기 때문에 RowMapper를 사용하여 한 줄씩 처리 할 수 있다.
public interface NoticeRepository extends JpaRepository<Notice, Long> {
}
JpaRepository<"@Entity 클래스", "@Id 의 데이터 타입">를 상속받는 interface 로 선언한다.
Spring Data JPA에 의해 자동으로 Bean 등록이 된다.
제네릭스의 @Entity 클래스 위치에 Notice Entity를 추가했기 때문에 해당 NoticeRepository는 DB의 notice 테이블과 연결되어 CRUD 작업을 처리하는 인터페이스가 되었다.
참고자료
스파르타코딩클럽 Spring Master 1,2주차 내용