JPA Auditing으로 생성 시간/수정시간 자동화
Java8버전부터 LocalDate와 LocalDateTime이 등장했다.
LocalDate가 나오기 전 Date나 Calendar클래스에는 다음과 같은 문제가 있었다.
- 불변 객체가 아니어서 멀티 쓰레드 환경에서 문제가 발생할 수 있었다.
- Calendar는 월(month) 설계가 잘못 되었다.- 10월을 나타내는 Calendar.OCTOBER의 숫자 값이 10이 아니고 9였다.
 
이러한 문제점을 LocalDate가 해결했다.
JPA Auditing사용하기
@Getter
@MappedSuperclass
@EntityListeners(AuditingEntityListener.class)
public class BaseTimeEntity {
    @CreatedDate
    private LocalDateTime createdDate;
    @LastModifiedDate
    private LocalDateTime modifiedDate;
}- @MappedSuperclass
 JPA Entity클래스들이 BaseTimeEntity를 상속할 경우 해당 클래스의 필드 또한 칼럼으로 인식하도록 한다.
- @EntityListeners(AuditingEntityListener.class)
 BaseTimeEntity클래스에 Auditing기능을 적용한다.
- @CreatedDate || @LastModifiedDate
 이름에서 유추 가능하듯이 생성 날짜, 수정 날짜가 자동 지정된다.
Entity클래스에서 BaseTimeEntity를 상속
...
...
public class Posts extends BaseTimeEntity {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;
    ...
    ...
Application클래스
JPA Auditing기능을 추가하려면 Application클래스에 @EnableJpaAuditing을 추가해야 한다.
@EnableJpaAuditing
@SpringBootApplication
public class BootexApplication {
    public static void main(String[] args) {
        SpringApplication.run(BootexApplication.class, args);
    }
}테스트
   @Test
    public void testBaseTimeEntity() {
        LocalDateTime now = LocalDateTime.of(2020,9,15,0,0,0);
        //insert
        postsRepository.save(Posts.builder()
            .title("title")
            .content("content")
            .author("author")
            .build());
        //조회
        List<Posts> postsList = postsRepository.findAll();
        //첫 번째 게시물
        Posts post = postsList.get(0);
        System.out.print(">>>>>>>>>>>>>>>>>>>>> createDate : " + post.getCreatedDate() +
                " modifiedDate : " + post.getModifiedDate());
        assertThat(post.getCreatedDate()).isAfter(now);
        assertThat(post.getModifiedDate()).isAfter(now);
    }결과

'Spring' 카테고리의 다른 글
| [Security] 현재 로그인한 사용자 정보 가져오기 (0) | 2021.01.23 | 
|---|---|
| 머스태치Mustache (0) | 2020.09.16 | 
| 등록/수정/조회 API (0) | 2020.09.14 | 
| Spring Boot 게시판 만들기 (0) | 2020.09.14 | 
| Spring Data JPA (0) | 2020.09.14 |