[SpringBoot] JPA Auditing

C____JIN·2022년 10월 13일
0

SpringBoot

목록 보기
6/6
post-thumbnail

BaseTimeEntity.java

@Getter
@MappedSuperclass
@EntityListeners(AuditingEntityListener.class)
public abstract class BaseTimeEntity {

    @CreatedDate
    private LocalDateTime createdDate;

    @LastModifiedDate
    private LocalDateTime modifiedDate;
}
  • @MappedSuperclass : JPA Entity 클래스들이 해당 클래스를 상속할 경우 필드들도 칼럼으로 인식
  • @EntityListener(AuditionEntityListener.class)
    • Audition 기능을 포함
  • @CreatedDate : Entity가 생성되어 저장될 때 시간이 자동 저장
  • @Last<odifiedDate : 조회한 Entity의 값을 변경할 때 시간이 자동으로 저장

그 이후)
1. BaseTimeEntity 클래스를 적용할 Entity에 상속받도록 적용
2. Application 클래스에 활성화 어노테이션 추가

  • @EnableJpaAuditing

테스트 코드 작성

@Test
public void BaseTimeEntity_등록() {
    //given
    LocalDateTime now = LocalDateTime.of(2022, 6, 4, 0, 0 ,0);
    postsRepository.save(Posts.builder()
            .title("title")
            .content("content")
            .author("author")
            .build());

    //when
    List<Posts> postsList = postsRepository.findAll();

    //then
    Posts posts = postsList.get(0);

    System.out.println(">>>>>>>>>> createDate=" + posts.getCreatedDate()+", modifiedDate=" + posts.getModifiedDate());

    assertThat(posts.getCreatedDate()).isAfter(now);
    assertThat(posts.getModifiedDate()).isAfter(now);
}

확인

참고

이동욱, 스프링 부트와 AWS로 혼자 구현하는 웹 서비스

profile
개발 블로그🌐 개발일지💻

0개의 댓글