@EnableJpaAuditing 추가@EntityListeners(AuditingEntityListener.class) 추가:: AuditorAware 구현체
- 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에 AuditorAware 빈 이름 설정@EnableJpaAuditing(auditorAwareRef = "userAuditorAware") // auditorAware 의 빈이름을 넣어준다.
생성 > 수정 > 삭제 이 흐름을 엔티티 라이프 사이클 이벤트라고 한다.@PostConstruct 의 원리와 같다.전 : @PrePersist : EntityManager 가 엔티티를 영속성상태로 만들기 직전에 메소드 수행
후 : @PostPersist : EntityManager 가 엔티티를 영속성상태로 만든 직후에 메소드 수행
전 : @PreUpdate : EntityManager 가 엔티티를 갱신상태로 만들기 직전에 메소드 수행
후 : @PostUpdate : EntityManager 가 엔티티를 갱신상태로 만든 직후에 메소드 수행
전 : @PerRemove : EntityManager 가 엔티티를 삭제상태로 만들기 직전에 메소드 수행
후 : @PostRemove : : EntityManager 가 엔티티를 삭제상태로 만든 직후에 메소드 수행
과제
ContextHolder + 엔티티 라이프 사이클 이벤트(@PrePersist, @PreUpdate) 사용해서 createdBy, modifiedBy 구현