데이터베이스에 저장된 컬럼을 접근할 때 생성할 때는 생성일, 변경할 때는 변경일이 있어야지 관리하고 기록할 수 있습니다. 이는 중요 Entity 마다 중복적으로 생성일, 변경일을 클래스 변수로 가져야 합니다. 따라서 이 중복되는 상황을 BaseTimeEntity 추상 클래스로 뽑아내고 Entity는 이를 상속하는 형식으로 Entity를 만듭니다.
@EntityListeners(AuditingEntityListener.class)
@MappedSuperclass
@Getter
public abstract class BaseTimeEntity {
@CreatedDate
@Column(updatable = false)
private LocalDateTime createdDate;
@LastModifiedDate
private LocalDateTime lastModifiedDate;
}
BaseTimeEntity 클래스는 모든 Entity의 상위클래스가 되어 Entity들의 수정 및 생성 필드를 자동으로 관리합니다.
@EntityListeners(AuditingEntityListener.class): 해당 클래스에 Auditing 기능을 포함
@MappedSuperclass: JPA Entity 클래스들이 BaseTimeEntity를 상속할 경우 날짜 필드도 칼럼으로 인식
@EntityListeners(AuditingEntityListener.class)
@Column(updatable = false) : createdDate의 컬럼 변경 불가
@EnableJpaAuditing
@SpringBootApplication
public class BoardApplication {
public static void main(String[] args) {
SpringApplication.run(BoardApplication.class, args);
}
}