1. Auditing이란?
Auditing(감사 로깅)이란 엔티티의 생성 및 수정 시점에 자동으로 등록일, 수정일, 등록자, 수정자를 기록하는 기능을 의미한다.
즉, 데이터가 언제 생성되었고, 언제 수정되었으며, 누가 변경했는지를 자동으로 저장하는 기능이다.
Auditing 기능이 필요한 이유
- 데이터 무결성 유지: 데이터를 생성하거나 수정한 사용자의 정보를 자동으로 추적
- 이력 관리: 엔티티의 변경 사항을 추적하여 감사(Audit) 로그로 활용
- 반복 코드 제거: 매번 createdDate, updatedDate를 수동으로 설정할 필요 없음
Spring Data JPA에서는 @EnableJpaAuditing 및 @CreatedDate, @LastModifiedDate 등의 어노테이션을 사용하여 이 기능을 간편하게 구현할 수 있다.
2. 순수 JPA를 이용한 Auditing 구현
Spring Data JPA 없이 순수 JPA만 사용하여 Auditing을 구현할 수도 있다.
이 경우 @PrePersist와 @PreUpdate를 활용하여 등록 및 수정 날짜를 자동으로 설정할 수 있다.
import jakarta.persistence.*;
import lombok.Getter;
import java.time.LocalDateTime;
@MappedSuperclass
@Getter
public class JpaBaseEntity {
@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();
}
}
주요 개념 정리
- @MappedSuperclass
- 공통 매핑 정보를 제공하는 부모 클래스 지정
- @PrePersist
- 엔티티가 처음 저장되기 전에 실행, 생성일과 수정일을 현재 시간으로 설정
- @PreUpdate
- 엔티티가 업데이트될 때 실행, 수정일을 현재 시간으로 변경
하지만 이 방법은 등록자, 수정자를 저장할 수 없고, Spring Security와 연동하여 사용자 정보를 저장하기 어렵다는 한계가 있다.
이를 해결하기 위해 Spring Data JPA의 Auditing 기능을 활용할 수 있다.
3. Spring Data JPA Auditing 적용
1) @EnableJpaAuditing 설정 추가
먼저 Spring Boot 애플리케이션 클래스에 @EnableJpaAuditing을 추가해야 한다.
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.data.jpa.repository.config.EnableJpaAuditing;
@EnableJpaAuditing
@SpringBootApplication
public class DataJpaApplication {
public static void main(String[] args) {
SpringApplication.run(DataJpaApplication.class, args);
}
}
2) 공통 엔티티 클래스 생성
Spring Data JPA는 @CreatedDate, @LastModifiedDate 애노테이션을 제공하여 자동으로 날짜를 기록할 수 있도록 지원다.
import jakarta.persistence.*;
import lombok.Getter;
import org.springframework.data.annotation.CreatedDate;
import org.springframework.data.annotation.LastModifiedDate;
import org.springframework.data.jpa.domain.support.AuditingEntityListener;
import java.time.LocalDateTime;
@MappedSuperclass
@EntityListeners(AuditingEntityListener.class)
@Getter
public class BaseEntity {
@CreatedDate
@Column(updatable = false)
private LocalDateTime createdDate;
@LastModifiedDate
private LocalDateTime lastModifiedDate;
}
주요 개념 정리
- @EntityListeners(AuditingEntityListener.class)
- Auditing 기능을 활성화하는 JPA 엔티티 리스너
- @CreatedDate
- 엔티티가 저장될 때 자동으로 등록일 설정
- @LastModifiedDate
- 엔티티가 수정될 때 자동으로 수정일 갱신
4. 등록자 및 수정자 정보 저장
Auditing을 활용하여 등록자와 수정자도 함께 저장할 수 있다.
import jakarta.persistence.*;
import lombok.Getter;
import org.springframework.data.annotation.CreatedBy;
import org.springframework.data.annotation.LastModifiedBy;
import org.springframework.data.jpa.domain.support.AuditingEntityListener;
@MappedSuperclass
@EntityListeners(AuditingEntityListener.class)
@Getter
public class BaseEntity extends BaseTimeEntity {
@CreatedBy
@Column(updatable = false)
private String createdBy;
@LastModifiedBy
private String lastModifiedBy;
}
등록자 및 수정자 설정 (AuditorAware)
AuditorAware 인터페이스를 구현하여 현재 사용자 정보를 반환해야 한다.
import org.springframework.context.annotation.Bean;
import org.springframework.data.domain.AuditorAware;
import org.springframework.stereotype.Component;
import java.util.Optional;
import java.util.UUID;
@Component
public class AuditorAwareImpl implements AuditorAware<String> {
@Override
public Optional<String> getCurrentAuditor() {
return Optional.of(UUID.randomUUID().toString()); // 실무에서는 로그인 정보를 반환
}
}
5. 실무에서 Spring Security와 연계
실무에서는 Spring Security의 SecurityContextHolder를 이용해 로그인한 사용자의 정보를 가져와 등록자 및 수정자로 활용할 수 있다.
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;
import org.springframework.data.domain.AuditorAware;
import java.util.Optional;
@Component
public class SecurityAuditorAware implements AuditorAware<String> {
@Override
public Optional<String> getCurrentAuditor() {
Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
if (authentication == null || !authentication.isAuthenticated()) {
return Optional.empty();
}
return Optional.of(authentication.getName());
}
}
6. 정리
- Auditing은 생성 및 수정 정보를 자동으로 저장하는 기능
- 순수 JPA에서는 @PrePersist, @PreUpdate를 사용
- Spring Data JPA에서는 @CreatedDate, @LastModifiedDate 활용
- 등록자/수정자는 @CreatedBy, @LastModifiedBy 및 AuditorAware로 처리
- Spring Security와 연동하여 로그인 사용자 정보를 활용 가능 🚀
'Backend > JPA' 카테고리의 다른 글
JPA (Spring Data JPA) - JPA 페이징과 정렬 처리 방법 (0) | 2025.03.12 |
---|---|
JPA (Spring Data JPA) - 컨트롤러 파라미터에서 엔티티의 ID를 자동으로 엔티티 객체로 변환하는 방법 (도메인 클래스 컨버터) (0) | 2025.03.12 |
JPA (Spring Data JPA) - 사용자 정의 리포지토리 개념과 구현 방법 (0) | 2025.03.12 |
JPA (Spring Data JPA) - 쿼리 메소드 기능 (예제 코드) (0) | 2025.03.11 |
JPA - 값 타입 매핑: 기본 개념부터 실무 적용까지 (0) | 2025.02.27 |