51. 게시글 수정

박선규's avatar
Mar 18, 2024
51. 게시글 수정
조회하면 영속화 된 객체가된는데 이 객체를 상태를 변경한다.
트랜잭션이 안돼있으면 업데이트가 안된다 당연한게 트랜잭션이 종료해야 업데이트 쿼리를 날리기 때문이다.
 
noresultexception이 뜨면 db에서 터진게 아니고 자바에서 파싱하다가 터진거다.
 

1.DTO 만들기

notion image
BoardRequest
@Data public static class UpdateDTO{ private String title; private String content ; private String username ; }
클라이언트의 데이터를 DTO 를 통해 받는다.
@NoArgsConstructor // 빈생성자가 필요 @Entity @Data @Table(name = "board_tb") public class Board { @Id @GeneratedValue (strategy = GenerationType.IDENTITY) private Integer id; private String title; private String content; private String username; @CreationTimestamp // persistance centext 에 전달될 때 자동으로 주입됨. private Timestamp createdAt; public void update(BoardRequest.UpdateDTO requestDTO){ this.title = requestDTO.getTitle(); this.content = requestDTO.getContent(); this.username = requestDTO.getUsername(); } }
📌
DTO를 편하게 받기 위해 update 메서드를 만든다.
 

2. 레파지토리

@Transactional public void updateById(Integer id,BoardRequest.UpdateDTO requestDTO) { Board board = findById(id); board.update(requestDTO); //영속화된 객체의 상태를 변경하고, 트랜잭션이 종료되면 더티체킹이 완료된다. }

꿀팁

업데이트를 하든 삭제를하든간에 조회를 한번하고 실행 하는것은 기본기다. 왜냐하면 그 사이에 값이 바꼈을 수 있기 때문이다.
EX)
 

Test

@Test public void updateById_test(){ // given int id = 1; String title = "제목수정1"; // when Board board = boardPersistRepository.findById(id); board.setTitle(title); em.flush(); //then }//더티 체킹
조회해서 상태를 변경하는 것을 더티체킹이라고한다.
@Test public void updateById_test(){ // given int id = 1; String title = "제목수정1"; // when Board board = boardPersistRepository.findById(id); board.setTitle(title); em.flush(); //then }//더티 체킹
(영속성에 있는 객체의 상태를 바꾼고 트랜잭션이 종료되면 더티 체킹(쿼리)이 실행.)
 

4. 컨트롤러

@GetMapping("/board/{id}/update-form") public String updateForm(@PathVariable Integer id,HttpServletRequest request){ Board board = boardPersistRepository.findById(id); request.setAttribute("board",board); return "board/update-form"; } @PostMapping("/board/{id}/update") public String update(@PathVariable Integer id,BoardRequest.UpdateDTO requestDTO){ boardPersistRepository.updateById(id,requestDTO); return "redirect:/board/"+id ; }
Share article

p4rksk