본문 바로가기

개발/Spring

[SpringBoot] JPA Auditing으로 생성시간/수정시간 자동화하기

 

 

  • Entity에는 해당 데이터의 생성시간, 수정시간을 포함
    • 차후 유지보수에 있어 중요한 정보
    • DB에 insert 하기 전, update 하기 전에 날짜 데이터를 등록/수정하는 코드가 필요
    • 단순하고 반복적인 코드를 줄이고자 JPA Auditing 사용

 

//생성일 추가 코드 예제
public void savePosts() {
  ...
  posts.setCreateDate(new LocalDate());
  postsRepository.save(posts);
  ...
}

 

 


 

LocalDate 사용

  • LocalDate/LocalDateTime은 기본 날짜 타입인 Date의 문제를 고친 타입
  • Date와 Calendar 클래스의 문제점
    • 불변 객체가 아니다 - 멀티스레드 환경에서 언제든 문제가 발생할 수 있다.
    • Calendar는 Month 값 설계가 잘못됐다 - 0월부터 시작
    • https://d2.naver.com/helloworld/645609 참고

 

  • LocalDate와 LocalDateTime 데이터베이스 매핑 이슈가 Hibernate 5.2.10 버전에서 해결

 

 


 

 

- domain 패키지에 BaseTimeEntity 클래스 생성

  • 모든 Entity의 상위 클래스가 되어 Entity들의 createdDate, modifiedDate를 자동으로 관리하는 역할

 

import lombok.Getter;
import org.springframework.data.annotation.CreatedDate;
import org.springframework.data.annotation.LastModifiedDate;
import org.springframework.data.jpa.domain.support.AuditingEntityListener;

import javax.persistence.EntityListeners;
import javax.persistence.MappedSuperclass;
import java.time.LocalDateTime;

@Getter
@MappedSuperclass // JPA Entity 클래스들이 BaseTimeEntity를 상속할 경우 필드도 칼럼으로 인식
@EntityListeners(AuditingEntityListener.class) // 클래스에 Auditing 기능을 포함
public class BaseTimeEntity {
    
    @CreatedDate // Entity가 생성되어 저장될 때 시간이 자동 저장
    private LocalDateTime createdDate;
    
    @LastModifiedDate // 조회한 Entity의 값을 변경할 때 시간이 자동 저장
    private LocalDateTime modifiedDate;
}

 

- Application에 JPA Auditing을 활성화하는 어노테이션 추가

@EnableJpaAuditing // JPA Auditing 활성화
@SpringBootApplication
public class Application {
    public static void main(String[] args) {
        SpringApplication.run(Application.class, args);
    }
}

 

-Posts Entity에 BaseTimeDate를 상속하는 코드 추가

 


 

 

JPA Auditing 테스트

@Test
public void TestRegisterBaseTimeEntity() {
  //given
  LocalDateTime now = LocalDateTime.of(2022,9,8,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);
}

JPA Auditing test 결과

 

'개발 > Spring' 카테고리의 다른 글

[SpringBoot] Mustache를 이용하여 화면 만들기  (0) 2022.09.08
[SpringBoot] 머스테치 Mustache  (0) 2022.09.08
[SpringBoot] API, API Test  (0) 2022.09.08
[SpringBoot] Spring Data JPA  (0) 2022.09.07
[SpringBoot] JPA  (0) 2022.09.06