[스프링부트 blogV2] 3. 수정하기 - 더티체킹 이용

silver's avatar
Jan 11, 2025
[스프링부트 blogV2] 3. 수정하기 - 더티체킹 이용
Contents
BoardService

Board

@AllArgsConstructor @NoArgsConstructor // db에서 조회해서 가져온 RS를 디폴트 생성자를 호출해서 new하고 값을 채워준다.// defalut 생성자가 있어야 reflection해서 값을 매핑해서 가져올 수 있다. @Getter @Table(name="board_tb") @Entity public class Board { @Id //jakarta @GeneratedValue(strategy = GenerationType.IDENTITY) private Integer id; private String title; private String content; @CreationTimestamp // native query에서는 안먹음 private Timestamp createdAt; public void update(String title, String content) { this.title = title; this.content = content; } }
// 업데이트를 위한 의미있는 생성자 public void update(String title, String content) { this.title = title; this.content = content; }
update는 repository에서 직접 쿼리문을 날리는 것이 아니라 1. 필드들이 영속성 컨텍스트 안에 있는 것을 이용해 2. board의 필드를 업데이트 해주면 3. 더티체킹이 발생해 4. 자동으로 변경내용 반영을 위한 sql update문이 생성되어 트랜젝션 커밋 시 실행된다.
💡

Controller → Service → Repository → PC(Persistence Context) : 영속성 컨텍스트 → Database

 
table 클래스 안에 의미있는 생성자로서의 update 메서드를 만들어
Service레이어에서 업데이트 시 호출한다.

Service

@Transactional public void 게시글수정하기(int id, BoardRequest.UpdateDTO updateDTO) { Board board = boardRepository.findById(id) .orElseThrow(()->new RuntimeException("해당 id의 게시글이 없습니다:"+id)); board.update(updateDTO.getTitle(), updateDTO.getContent()); // 영속화된 객체상태 변경 - update + commit => 더티체킹 }
Share article

silver