Auditing 기능은 엔티티의 생성 및 수정 시점을 감시하여 생성일, 생성자, 수정일, 수정자를 자동으로 기록할 수 있으며, 이러한 생성일과 수정자는 엔티티가 공통적으로 가지는 컬럼이므로 중복 코드를 줄이기 위해 BaseEntity 클래스로 분리하여 다양한 방법으로 Auditing을 구현할 수 있습니다.
1. JPA으로 구현
1-1. 공통 관심사 엔티티 구현
@Getter
@MappedSuperclass
public abstract class BaseEntity {
@Column(updatable = false)
private LocalDateTime createdDate;
private LocalDateTime updatedDate;
@PrePersist
public void prePersist() {
ZonedDateTime koreaTime = ZonedDateTime.now(ZoneId.of("Asia/Seoul"));
LocalDateTime localDateTime = koreaTime.toLocalDateTime();
this.createdDate = localDateTime;
this.updatedDate = localDateTime;
}
@PreUpdate
public void preUpdate() {
updatedDate = ZonedDateTime.now(ZoneId.of("Asia/Seoul")).toLocalDateTime();
}
}
@MappedSuperclass는 JPA에서 엔티티 간 공통으로 사용되는 매핑 정보를 정의하기 위해 사용하는 애노테이션으로, 상속 관계 매핑과는 다르게 상위 클래스가 직접 엔티티로 사용되지 않으며, 하위 클래스가 실제로 데이터베이스 테이블에 매핑됩니다. 이를 통해 공통 필드를 상위 클래스에 정의하고 하위 클래스에서 이를 상속받아 사용할 수 있어 코드의 중복을 줄이고 관리 효율성을 높일 수 있습니다.
JPA 주요 이벤트 애노테이션
1. @PrePersist
- 엔티티가 데이터베이스에 저장되기 전에 호출됩니다.
- 주로 엔티티의 상태를 초기화하거나, 특정 필드를 설정하는 데 사용됩니다.
2. @PostPersist
- 엔티티가 데이터베이스에 저장된 후 호출됩니다.
- 주로 저장 후 후속 작업을 수행하는 데 사용됩니다.
3. @PreUpdate
- 엔티티가 데이터베이스에서 업데이트되기 전에 호출됩니다.
- 주로 업데이트 전에 상태를 검증하거나, 특정 필드를 수정하는 데 사용됩니다.
4. @PostUpdate
- 엔티티가 데이터베이스에서 업데이트된 후 호출됩니다.
- 주로 업데이트 후 후속 작업을 수행하는 데 사용됩니다.
5. @PreRemove
- 엔티티가 데이터베이스에서 삭제되기 전에 호출됩니다.
- 주로 삭제 전에 필요한 정리 작업을 수행하는 데 사용됩니다.
7. @PostRemove
- 엔티티가 데이터베이스에서 삭제된 후 호출됩니다.
- 주로 삭제 후 후속 작업을 수행하는 데 사용됩니다.
8. @PostLoad
- 엔티티가 데이터베이스에서 로드된 후 호출됩니다.
PreXX는 작업이 시작되기 전에 호출되는 메소드이고, PostXX는 작업이 완료된 후에 호출되는 메소드로, 이 두 메소드는 작업의 전후에 특정 로직을 실행하기 위해 사용됩니다.
1-2. 공통 관심사 적용
public class Member extends BaseEntity
2. Spring Data JPA으로 구현
2-1. Spring Data JPA Auditing 기능 활성화
@EnableJpaAuditing // Auditing 기능 활성화
@SpringBootApplication
public class DataJpaApplication {
public static void main(String[] args) {
SpringApplication.run(DataJpaApplication.class, args);
}
}
메인 클래스에 @EnableJpaAuditing 애너테이션을 추가하여 Auditing 기능을 활성화합니다.
2-2. 공통 관심사 엔티티 생성
@EntityListeners(AuditingEntityListener.class)
@MappedSuperclass
@Getter
public class BaseEntity {
@CreatedDate // 데이터 생성 날짜 자동 저장
@Column(updatable = false)
private LocalDateTime createdDate;
@LastModifiedDate // 데이터 수정 날짜 자동 저장
private LocalDateTime lastModifiedDate;
@CreatedBy // 데이터 생성자 자동 저장
@Column(updatable = false)
private String createdBy;
@LastModifiedBy // 데이터 수정자 자동 저장
private String lastModifiedBy;
}
@EntityListeners(AuditingEntityListener.class)는 Spring Data JPA에서 제공하는 이벤트 리스너로, Auditing에 이벤트(등록, 수정)가 발생할 때마다 Auditing 정보를 자동으로 반영할 수 있도록 준비해줍니다. 이를 통해 엔티티가 생성되거나 수정될 때, @CreatedDate, @LastModifiedDate, @CreatedBy, @LastModifiedBy와 같은 Auditing 애너테이션이 설정된 필드에 적절한 값이 자동으로 채워지게 됩니다.
2-3. AuditorAware 구현
등록자, 수정자를 자동으로 데이터를 가져오는게 아니라 AuditorAware 구현체를 생성하여 등록자(createdBy)와 수정자(lastModifiedBy) 정보를 자동으로 가져오는 방법은 다음과 같습니다.
AuditorAware 인터페이스 구현 - Spring Security
public class AuditorAware implements AuditorAware<String> {
@Override
public String getCurrentAuditor() {
Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
if (authentication == null || !authentication.isAuthenticated()) {
return null;
}
return (String) authentication.getPrincipal();
}
}
AuditorAware 클래스를 만들어 AuditorAware<String> 인터페이스를 구현합니다. 이 클래스에서는 현재 사용자의 인증 정보를 가져와서, 인증된 사용자의 이름을 반환하는 getCurrentAuditor() 메서드를 정의합니다. 만약 인증 정보가 없거나 사용자가 인증되지 않았다면 null을 반환합니다.
Spring Data JPA AuditConfig 설정
@Configuration
@EnableJpaAuditing
public class JpaAuditConfig {
@Bean
public AuditorAware<String> auditorProvider() {
return new AuditorAware();
}
}
엔티티 적용
@Entity
@Getter
@NoArgsConstructor(access = AccessLevel.PROTECTED)
public class Member extends BaseEntity
마지막으로, 공통 관심사인 BaseEntity를 상속받는 엔티티에 Auditing 기능을 적용합니다. 예를 들어, Member 엔티티는 BaseEntity를 상속받아 Auditing 정보를 자동으로 관리할 수 있습니다.
참고자료
https://docs.spring.io/spring-data/jpa/reference/auditing.html
Auditing :: Spring Data JPA
Spring Data provides sophisticated support to transparently keep track of who created or changed an entity and when the change happened.To benefit from that functionality, you have to equip your entity classes with auditing metadata that can be defined eit
docs.spring.io
https://www.baeldung.com/database-auditing-jpa
Spring Data JPA - Auditing
오늘은 Spring Data JPA에서 제공하는 유용한 기능인 Auditing에 대해서 정리해보려고 합니다. 백엔드 그리고 DB 쪽 개발을 하다 보면 테이블에 공통적으로 들어가는 Column이 있습니다. 등록한 날짜 마
wangtak.tistory.com
'Spring' 카테고리의 다른 글
[Spring Data JPA] Projections 간단 정리 (0) | 2025.01.20 |
---|---|
[Spring Data JPA] 직접 PK 값을 설정하면 발생하는 문제 - Persistable (0) | 2025.01.15 |
[Spring Data JPA] Custom Repository - 사용자 정의 리포지토리 (0) | 2025.01.13 |
[Spring Data JPA] 페이징과 정렬 (1) | 2025.01.03 |
[Spring + Prometheus + Grafana] 간단한 커스텀 메트릭 구현 #2 - @Counted, @Timed, MeterBinder (4) | 2024.10.20 |