Spring

[Spring] JPA로 update 작업하기

quedevel 2020. 3. 13. 18:47
728x90
반응형

사실 update란 메소드가 있을줄 알았다....ㅋㅋㅋ

없는걸 깨닫고 현재 게시글 정보를 받아와 수정한후 다시 save를 하니 업데이트는 되었는데....

게시글 도메인에 @Builder로 생성하도록 잡아놨던걸 @Setter를 @Getter 로 바꿔주었다... 나의 한계인가

Board.java

@Table(name = "tbl_board")
@NoArgsConstructor
@Setter
@Getter
@Entity
public class Board extends AbstractDate {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long bno;

    private String title;

    private String writer;

    private String content;
}

service layer에서 처리

BoardService.java

    @Transactional
    public Long modify(Board board) {
        Board updatedBoard = boardRepository.findById(board.getBno()).get();
        updatedBoard.setTitle(board.getTitle());
        updatedBoard.setContent(board.getContent());
        return boardRepository.save(updatedBoard).getBno();
    }

 

결과 Query가 3번 들어간다

Hibernate: 
    select
        board0_.bno as bno1_0_0_,
        board0_.created_date as created_2_0_0_,
        board0_.modified_date as modified3_0_0_,
        board0_.content as content4_0_0_,
        board0_.title as title5_0_0_,
        board0_.writer as writer6_0_0_ 
    from
        tbl_board board0_ 
    where
        board0_.bno=?
Update
Hibernate: 
    select
        board0_.bno as bno1_0_0_,
        board0_.created_date as created_2_0_0_,
        board0_.modified_date as modified3_0_0_,
        board0_.content as content4_0_0_,
        board0_.title as title5_0_0_,
        board0_.writer as writer6_0_0_ 
    from
        tbl_board board0_ 
    where
        board0_.bno=?
Hibernate: 
    update
        tbl_board 
    set
        created_date=?,
        modified_date=?,
        content=?,
        title=?,
        writer=? 
    where
        bno=?

찾아올때 1번

다시 저장할때 1번

업데이트 1번

기존의 BoardService.java 수정

    @Transactional
    public Long modify(Board board) {
        return boardRepository.save(board).getBno();
    }

화면에서 데이터가 들어올때 bno를 함께주면 JPA가 알아서 판단해서

UPDATE를 진행함

Board.java 도 @Builder로 변경하였다

728x90
반응형