데이터베이스의 거의 모든 테이블에는 데이터가 추가된 시간이나 수정된 시간 등이 컬럼으로 작성된다.
@MappedSupperClass 를 이용해서 공통으로 사용되는 컬럼들을 지정하고 해당 클래스를 상속해서 이를 손쉽게 처리하고자 한다.
package com.example.commhere.entity;
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.Column;
import javax.persistence.EntityListeners;
import javax.persistence.MappedSuperclass;
import java.time.LocalDateTime;
@EntityListeners(value = { AuditingEntityListener.class })
@MappedSuperclass
@Getter
abstract class Base {
@CreatedDate
@Column(name = "created_date", updatable = false)
private LocalDateTime createdDate;
@LastModifiedDate
@Column(name = "modified_date")
private LocalDateTime modifiedDate;
}
<aside> ✅ 가장 중요한 부분은 Spring Data JPA 의 AuditingEntityListener 를 지정하는 부분이다. AuditingEntityListener 를 적용하면 엔티티가 데이터베이스에 추가되거나 변경될 때 자동으로 시간 값을 지정할 수 있다. AuditingEntityListener 를 활성화 시키기 위해서는 프로젝트 설정에 @EnableJpaAuditing 을 추가해야 한다.
</aside>
package com.example.commhere;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.data.jpa.repository.config.EnableJpaAuditing;
@SpringBootApplication
@EnableJpaAuditing
public class CommhereApplication {
public static void main(String[] args) {
SpringApplication.run(CommhereApplication.class, args);
}
}