본문 바로가기
Spring/SpringDataJPA

[spring / JPA]spring JPA auditing ; 시간 자동화에 대하여

by SIXXXX_ 2022. 9. 12.
728x90

JPA Auditing : 생성시간, 수정 시간 자동화 하기

엔티티에는 해당 데이터의 생성 시간과 수정 시간을 포함한다.

언제 만들어졌는지, 언제 수정되었는지 등은 차후 유지보수에 중요 요소이다.

그래서 매번 dB 삽입하기 전, 갱신 전 날짜데이터를 등록/수정하는 코드가 여러군데 필요하다.

 

 

단순하고 반복적인 코드를 깔끔하게 정리하기 위해 JPA Auditing을 사용한다.

 

localDate, localDateTime 사용

 

BaseTimeEntity : 모든 Entity의 상위 클래스가 되어 Entity들의 cretedDate, modiftedDate를 자동으로 관리하는 역할

@Getter
@MapperSuperclass
@EntityListeners(AuditiingEntityM=Listener.class)
public abstract class BaseTimeEntity {
    @CreteDte
    private LocalDateTime createdDate;
    
    @LastModifiedDate
    private LocalDateTime modifiedDate;
    
}

 

  • @MappedSuperclass : JPA Entity 클래스들이 BaseTimeEntity 를 상속할 경우 필드들도 칼럼으로 인식
  • @EntityListeners(AuditingEntityLister.clss) : Auditing 기능 포함
  • @CreateDate : Entity가 생성되어 저장될때 시간이 자동저장된다.
  • @LastModifiedDate : 조회한 Entity 값을 변경할 때 시간이 자동저장된다.

Post 클래스

 ...
public class Posts extends BaseTimeEntity {
 ...

}

: BaseTimeEntity를 상속받도록 변경하기

 

 

Application 클래스에서 활성화 어노테이션 추가

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

@EnableJpaAuditing : JPA Auditing 활성화하기