[Spring] 생성시간, 수정시간 관리

손시연·2022년 11월 14일
0

spring-boot

목록 보기
10/10
  • 문제상황 : 많은 엔티티에서 생성시간, 수정시간 컬럼이 공통적으로 필요함
  • 해결 : 생성시간과 수정시간을 필드로 갖는 부모 클래스(BaseTime Class)를 상속받도록 하자! 코드의 중복을 줄임
@Getter
@MappedSuperclass
@EntityListeners(AuditingEntityListener.class)
public class BaseTime {

    @CreatedDate
    private LocalDateTime createdAt;

    @LastModifiedDate
    private LocalDateTime modifiedAt;
}
  • @MappedSuperclass : JPA Entity 클래스들이 BaseTime class를 상속할 경우 BaseTime class의 필드인 createdDate, modifiedDate를 인식하도록 함

    • @MappedSupperclass가 선언된 클래스는 Entity가 아니며 직접 생성해서 사용될 일이 없기 때문에 대부분 추상 클래스로 만들어짐.
  • @EntityListeners : PA Entity에서 이벤트가 발생할 때마다 특정 로직을 실행시킬 수 있는 어노테이션

    • AuditingEntityListener 클래스가 callback listener로 지정되어, Entity에서 이벤트가 발생할 때마다 특정 로직을 수행함
  • @CreatedDate : Entity가 생성되어 저장될 때 시간이 자동으로 저장

  • LastModifiedDate : 조회한 Entity의 값을 변경할 때 시간이 자동으로 저장

  • @EnableJpaAuditing : JPA Auditing(감시, 감사)을 위한 어노테이션. createdDate, modifiedDate처럼 DB에 데이터가 저장되거나 수정될 때 언제, 누가 했는지를 자동으로 관리

    • main 메서드에 적음
    @SpringBootApplication
     @EnableJpaAuditing
     public class XXXApplication {
    
    		 public static void main(String[] args) {
    			  SpringApplication.run(XXXApplication.class, args);
             }
    
     }
profile
Server Engineer

0개의 댓글