SpringData JPA Auditing

more·2023년 7월 27일
0

JPA 심화 2일차

목록 보기
4/5

엔티티의 이벤트를 감시하는 Auditing

  • Auditing 을 사용하면 엔티티를 누가 언제 생성/마지막 수정 했는지 자동으로 기록되게 할 수 있다.
// 만들어진 날짜
@CreatedDate
private Date created;

// 마지막으로 수정된 날짜
@LastModifiedDate
private Date updated;

// 만든 Account
@CreatedBy
@ManyToOne
private Account createdBy;

// 마지막으로 수정한 Account
@LastModifiedBy
@ManyToOne
private Account updatedBy;

보통 이렇게 사용함

Auditing 적용 방법

  1. 메인 애플리케이션 위에 @EnableJpaAuditing 추가
  2. 엔티티 클래스 위에 @EntityListeners(AuditingEntityListener.class) 추가
  3. 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());
        }
    }
  1. @EnableJpaAuditing에 AuditorAware 빈 이름 설정하기.
    @EnableJpaAuditing(auditorAwareRef = "userAuditorAware") // auditorAware 의 빈이름을 넣어준다.
  • 엔티티의 영속성이 변경되는 생성 > 수정 > 삭제 이 흐름을 엔티티 라이프 사이클 이벤트라고 한다.
    -> Auditing 도 이러한 엔티티의 라이프 사이클 이벤트를 통해 구현

엔티티 저장 이벤트

전 : @PrePersist : EntityManager 가 엔티티를 영속성상태로 만들기 직전에 메소드 수행

후 : @PostPersist : EntityManager 가 엔티티를 영속성상태로 만든 직후에 메소드 수행

엔티티 수정 이벤트

전 : @PreUpdate : EntityManager 가 엔티티를 갱신상태로 만들기 직전에 메소드 수행

후 : @PostUpdate : EntityManager 가 엔티티를 갱신상태로 만든 직후에 메소드 수행

엔티티 삭제 이벤트

전 : @PerRemove : EntityManager 가 엔티티를 삭제상태로 만들기 직전에 메소드 수행

후 : @PostRemove : : EntityManager 가 엔티티를 삭제상태로 만든 직후에 메소드 수행

profile
조금 더

0개의 댓글