본문 바로가기
Today I...

[TIL]JPA Auditing

by seeker00 2025. 2. 13.

JPA Auditing

개요

  • 엔티티의 이벤트를 감시하는 역할을 수행한다.
  • JPA Auditing 기능을 활용해 엔티티를 누가 언제 생성/수정했는지 자동으로 기록되게 할 수 있다.

Auditing 적용 방법

1. JpaConfig 생성

@Configuration
@EnableJpaAuditing
public class JpaConfig {

    @Bean
    public AuditorAware<Long> auditorProvider() {
        return new UserAuditorAware();
    }

}
  • 빈으로 AuditorAware의 구현체를 등록한다.

2. AuditorAware 구현체 생성

public class AuditorAwareImpl implements AuditorAware<Long> {

    @Override
    public Optional<Long> getCurrentAuditor() {
		Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
		if (authentication != null
			&& authentication.isAuthenticated()
			&& authentication.getPrincipal() instanceof UserDetailsImpl userDetails) {
			return Optional.of(userDetails.getUserId());
		} else {
			// 인증된사용자 정보가 UserDetailsImpl이 아닌경우 빈값 반환
			return Optional.empty();
		}
    }

}
  • getCurrentAuditor 메소드를 오버라이드하여, 시큐리티 컨텍스트에 담긴 authentication 객체를 통해 유저 아이디 정보를 가져온다.

3. BaseEntity 생성

@EntityListeners(AuditingEntityListener.class)  
@MappedSuperclass  
@Getter  
public abstract class BaseEntity {

//등록일
@CreatedDate
private LocalDateTime createdDate;

//수정일
@LastModifiedDate
private LocalDateTime modifiedDate;

//등록자
@CreatedBy
private Long createdBy;

//수정자
@LastModifiedBy
private Long modifiedBy;
}
  • @EntityListeners와 @MappedSuperclass 어노테이션을 등록한다.

@MappedSuperclass 란?

  • 상속 관계 매핑은 부모 클래스와 자식 클래스를 모두 데이터베이스 테이블과 매핑한다.(구체적인 매핑 전략으로는 조인 전략, 단일 테이블 전략, 구현 클래스마다 테이블 전략이 있다.)
  • @MappedSuperclass 를 활용하면, 부모 클래스는 테이블과 매핑하지 않고, 부모 클래스를 상속받는 자식 클래스에게 매핑 정보만 제공할 수 있다.

참고 자료

'Today I...' 카테고리의 다른 글

오늘의 노트  (0) 2025.02.16
[TIL] 오늘 알게된 것  (0) 2025.02.14
[TIL]개발자에게 필요한 소프트 스킬에 대한 회고  (0) 2025.02.12
[TIL]도커 네트워크  (0) 2025.02.11
[TI...] 조금이라도 기억에 남겨보기  (0) 2021.08.24