// 만들어진 날짜
@CreatedDate
private Date created;
// 마지막으로 수정된 날짜
@LastModifiedDate
private Date updated;
// 만든 Account
@CreatedBy
@ManyToOne
private Account createdBy;
// 마지막으로 수정한 Account
@LastModifiedBy
@ManyToOne
private Account updatedBy;
보통 이렇게 사용함
createdAt, modifiedAt 은 구현체 없이 동작하지만 createdBy, modifiedBy 는 구현체가 필요
SpringSecurity 의 SecurityContextHolder 에서 인증정보안에 담긴 UserDetailsImpl 을 사용하여 user 객체를 가져와서 넣어준다.
예시 코드
@Service
public class UserAuditorAware implements AuditorAware<User> {
@Override
public Optional<User> getCurrentAuditor() {
Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
if (authentication == null || !authentication.isAuthenticated()) {
return Optional.empty();
}
return Optional.of(((UserDetailsImpl) authentication.getPrincipal()).getUser());
}
}
@EnableJpaAuditing(auditorAwareRef = "userAuditorAware") // auditorAware 의 빈이름을 넣어준다.생성 > 수정 > 삭제 이 흐름을 엔티티 라이프 사이클 이벤트라고 한다.전 : @PrePersist : EntityManager 가 엔티티를 영속성상태로 만들기 직전에 메소드 수행
후 : @PostPersist : EntityManager 가 엔티티를 영속성상태로 만든 직후에 메소드 수행
전 : @PreUpdate : EntityManager 가 엔티티를 갱신상태로 만들기 직전에 메소드 수행
후 : @PostUpdate : EntityManager 가 엔티티를 갱신상태로 만든 직후에 메소드 수행
전 : @PerRemove : EntityManager 가 엔티티를 삭제상태로 만들기 직전에 메소드 수행
후 : @PostRemove : : EntityManager 가 엔티티를 삭제상태로 만든 직후에 메소드 수행