ABOUT ME

-

Today
-
Yesterday
-
Total
-
  • [Spring Boot] JPA 게시판 만들기(3) - JPA Auditing 설정
    Spring Boot/2.3.x - JPA 게시판 만들기 2020. 7. 20. 16:08
    반응형

     일반적으로 테이블을 설계할 때 데이터의 생성시간과 수정시간 컬럼을 포함하는데, JPA Auditing을 사용하면 생성시간과 수정시간을 자동으로 관리할 수 있습니다.


    1.BaseTimeEntity 구현

    com.rest.api.common.domain 패키지를 생성한 후 BaseTimeEntity 클래스르 추가하세요.

    BaseTimeEntity.java

    더보기
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    package com.rest.api.common.domain;
     
    import java.time.LocalDateTime;
     
    import javax.persistence.Column;
    import javax.persistence.EntityListeners;
    import javax.persistence.MappedSuperclass;
     
    import org.springframework.data.annotation.CreatedDate;
    import org.springframework.data.annotation.LastModifiedDate;
    import org.springframework.data.jpa.domain.support.AuditingEntityListener;
     
    import lombok.Getter;
     
    @Getter
    @MappedSuperclass
    @EntityListeners(AuditingEntityListener.class)
    public abstract class BaseTimeEntity {
     
        @CreatedDate
        @Column(name = "created_date")
        private LocalDateTime createdDate;
     
        @LastModifiedDate
        @Column(name = "modifiedDate")
        private LocalDateTime modifiedDate;
    }
    cs

    @MappedSuperclass

    JPA Entity 클래스들이 BaseTimeEntity을 상속할 경우 필드들도 컬럼으로 인식할 수 있도록 합니다.

    @EntityListeners(AuditingEntityListener.class)

    BaseTimeEntity 클래스에 Auditing 기능을 포함하도록 합니다.

    @CreatedDate

    Entity가 생성되어 저장될 때 시간이 자동으로 저장되도록 합니다.

    @LastModifiedDate

    Entity의 값을 변경할 때 시간이 자동으로 저장되록 합니다.


    2.Board 수정

    Board 클래스가 BaseTimeEntity를 상속받도록 수정하세요.

    Board.java

    더보기
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    package com.rest.api.board.domain;
     
    import javax.persistence.Column;
    import javax.persistence.Entity;
    import javax.persistence.GeneratedValue;
    import javax.persistence.GenerationType;
    import javax.persistence.Id;
    import javax.persistence.Lob;
    import javax.persistence.Table;
     
    import com.rest.api.common.domain.BaseTimeEntity;
     
    import lombok.Builder;
    import lombok.Getter;
    import lombok.NoArgsConstructor;
     
    @Getter
    @NoArgsConstructor
    @Entity
    @Table(name = "tbl_board")
    public class Board extends BaseTimeEntity {
     
        @Id
        @GeneratedValue(strategy = GenerationType.IDENTITY)
        @Column(name = "board_seq")
        private Long boardSeq;
     
        @Lob
        @Column(name = "board_subject")
        private String boardSubject;
     
        @Column(name = "board_writer")
        private String boardWriter;
     
        @Lob
        @Column(name = "board_content")
        private String boardContent;
     
        @Builder
        public Board(String boardSubject, String boardWriter, String boardContent) {
            this.boardSubject = boardSubject;
            this.boardWriter = boardWriter;
            this.boardContent = boardContent;
        }
     
        public void update(String boardSubject, String boardContent) {
            this.boardSubject = boardSubject;
            this.boardContent = boardContent;
        }
    }
    cs


    3.Application 수정

    JPA Auditing 어노테이션들을 활성화하기 위해 Application 클래스에 @EnableJpaAuditing 어노테이션을 추가하세요.

    JpaSampleApplication.java

    더보기
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    package com.rest.api;
     
    import org.springframework.boot.SpringApplication;
    import org.springframework.boot.autoconfigure.SpringBootApplication;
    import org.springframework.boot.builder.SpringApplicationBuilder;
    import org.springframework.boot.web.servlet.support.SpringBootServletInitializer;
    import org.springframework.data.jpa.repository.config.EnableJpaAuditing;
     
    @EnableJpaAuditing
    @SpringBootApplication
    public class JpaSampleApplication extends SpringBootServletInitializer {
     
        public static void main(String[] args) {
            SpringApplication.run(JpaSampleApplication.class, args);
        }
     
        @Override
        protected SpringApplicationBuilder configure(SpringApplicationBuilder builder) {
            return builder.sources(JpaSampleApplication.class);
        }
    }
    cs


    4.JPA Auditing 테스트 코드 구현

    com.rest.api.board.repository 패키지를 생성한 후 BoardRepositoryTest 클래스를 추가하세요.

    BoardRepositoryTest.java

    더보기

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    package com.rest.api.board.repository;
     
    import static org.assertj.core.api.Assertions.assertThat;
     
    import java.time.LocalDateTime;
    import java.util.List;
     
    import org.junit.Test;
    import org.junit.runner.RunWith;
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.boot.test.context.SpringBootTest;
    import org.springframework.test.context.junit4.SpringRunner;
     
    import com.rest.api.board.domain.Board;
     
    @RunWith(SpringRunner.class)
    @SpringBootTest
    public class BoardRepositoryTest {
     
        @Autowired
        BoardRepository boardRepository;
     
        @Test
        public void baseTimeEntity() {
     
            String boardSubject = "게시글_제목_저장_01";
            String boardWriter = "게시글_작성자_저장_01";
            String boardContent = "게시글_내용_저장_01";
     
            LocalDateTime now = LocalDateTime.of(2020720000);
     
            boardRepository.save(Board.builder()
                                      .boardSubject(boardSubject)
                                      .boardWriter(boardWriter)
                                      .boardContent(boardContent)
                                      .build());
     
            List<Board> boardList = boardRepository.findAll();
            Board board = boardList.get(boardList.size() - 1);
     
            System.out.println("==== ==== ==== ==== ==== ==== ==== ====");
            System.out.println("createdDate : " + board.getCreatedDate());
            System.out.println("modifiedDate : " + board.getModifiedDate());
            System.out.println("==== ==== ==== ==== ==== ==== ==== ====");
     
            assertThat(board.getCreatedDate()).isAfter(now);
            assertThat(board.getModifiedDate()).isAfter(now);
        }
    }
    cs

    Github Repository - https://github.com/tychejin1218/jpa-sample

    반응형

    댓글

Designed by Tistory.