거의 모든 테이블에 들어가는 등록시간, 수정시간과 등록자, 수정자 정보는 BaseEntity를 만들어 모든 엔티티가 상속받게 하여 편하게 관리할 수 있다.
JPA에서도 이와 관련한 기능을 제공하는데,
@PrePersist를 붙인 메소드를 생성하여 새로운 객체를 영속관리하기 직전 createdTime과 updatedTime을 설정하거나 @PreUpdate를 붙인 메소드를 통해 updatedTime을 새로 바꿔주는 것이다.
@Getter
@MappedSuperclass
@ToString(of={"createdDate","updatedDate"})
public class BaseEntity {
@Column(updatable = false)
private LocalDateTime createdDate;
private LocalDateTime updatedDate;
@PrePersist
public void prePersist(){
LocalDateTime now = LocalDateTime.now();
createdDate = now;
updatedDate = now;
}
@PreUpdate
public void preUpdate(){
updatedDate = LocalDateTime.now();
}
}
이는 JPA기본 스펙이며 Spring Data JPA에서는 더 간소화된 형태로 관리할 수 있도록 어노테이션을 제공하는데,
@EntityListeners(AuditingEntityListener.class)
@MappedSuperclass
@Getter
public class BaseEntity {
@CreatedDate
@Column(updatable = false)
private LocalDateTime createdDate;
@LastModifiedDate
private LocalDateTime lastModifiedDate;
}
와 같이 baseEntity에는 각 필드 위에 @CreatedDate, @LastModifiedDate로 필드의 의미를 명시하고 class에는 @EntityListeners(AuditingEntityListener.class) 어노테이션을 추가한 뒤
@SpringBootApplication
@EnableJpaAuditing
public class DataApplication {
public static void main(String[] args) {
SpringApplication.run(DataApplication.class, args);
}
}
어플리케이션이 시작되는 클래스에 @EnableJpaAuditing를 추가하면 된다.
시간 뿐 아니라 생성자, 수정자도 Spring Data Jpa를 통해 편하게 관리할 수 있는데
@EntityListeners(AuditingEntityListener.class)
@MappedSuperclass
@Getter
public class BaseEntity {
@CreatedDate
@Column(updatable = false)
private LocalDateTime createdDate;
@LastModifiedDate
private LocalDateTime lastModifiedDate;
@CreatedBy
@Column(updatable = false)
private String createdBy;
@LastModifiedBy
private String updatedBy;
}
와 같이 마찬가지로 어노테이션을 추가하여 의미를 명시하고
@Bean
public AuditorAware<String> auditorProvider(){
return () -> "세션의 로그인 정보를 가져와 return하는 로직";
}
로그인 정보를 return하는 로직을 가진 AuditorAware를 리턴하는 auditorProvider라는 빈을 등록하면 세션의 로그인 정보를 가져와 알아서 생성자와 수정자에 넣어준다. (빈 등록 시 세션에서 로그인 정보를 가져오는 로직은 직접 추가해야 한다.)