Published 2022. 7. 21. 22:12

엔티티를 생성, 변경할 때 변경한 사람과 시간을 추적하고 싶으면?

등록일
수정일
등록자
수정자

 

순수 JPA 사용

우선 등록일, 수정일 적용

package study.datajpa.entity;
@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();
 }
}

 

public class Member extends JpaBaseEntity {}

 

확인 코드

@Test
public void JpaEventBaseEntity() throws Exception {
 //given
 Member member = new Member("member1");
 memberRepository.save(member); //@PrePersist
 Thread.sleep(100);
 member.setUsername("member2");
 em.flush(); //@PreUpdate
 em.clear();
 //when
 Member findMember = memberRepository.findById(member.getId()).get();
 //then
 System.out.println("findMember.createdDate = " findMember.getCreatedDate());
 System.out.println("findMember.updatedDate = " findMember.getUpdatedDate());
}

 

JPA 주요 이벤트 어노테이션

@PrePersist, @PostPersist
@PreUpdate, @PostUpdate

 

 

스프링 데이터 JPA 사용

설정

@EnableJpaAuditing 스프링 부트 설정 클래스에 적용해야함

@EntityListeners(AuditingEntityListener.class) 엔티티에 적용

 

사용 어노테이션

@CreatedDate
@LastModifiedDate
@CreatedBy
@LastModifiedBy

 

 

스프링 데이터 Auditing 적용 - 등록일, 수정일

package study.datajpa.entity;
@EntityListeners(AuditingEntityListener.class)
@MappedSuperclass
@Getter
public class BaseEntity {
 @CreatedDate
 @Column(updatable = false)
 private LocalDateTime createdDate;
 @LastModifiedDate
 private LocalDateTime lastModifiedDate;
}

 

스프링 데이터 Auditing 적용 - 등록자, 수정자

package jpabook.jpashop.domain;
@EntityListeners(AuditingEntityListener.class)
@MappedSuperclass
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;
}

 

등록자, 수정자를 처리해주는 AuditorAware 스프링 빈 등록

@EnableJpaAuditing
@SpringBootApplication
public class DataJpaApplication {

	public static void main(String[] args) {
		SpringApplication.run(DataJpaApplication.class, args);
	}

	@Bean
	public AuditorAware<String> auditorProvider() {
		return () -> Optional.of(UUID.randomUUID().toString());
	}
}

실무에서는 세션 정보나, 스프링 시큐리티 로그인 정보에서 ID를 받음

 

 

> 참고: 실무에서 대부분의 엔티티는 등록시간, 수정시간이 필요하지만, 등록자, 수정자는 없을 수도 있다. 
그래서 다음과 같이 Base 타입을 분리하고, 원하는 타입을 선택해서 상속한다.

 

public class BaseTimeEntity {
 @CreatedDate
 @Column(updatable = false)
 private LocalDateTime createdDate;
 @LastModifiedDate
 private LocalDateTime lastModifiedDate;
}
public class BaseEntity extends BaseTimeEntity {
 @CreatedBy
 @Column(updatable = false)
 private String createdBy;
 @LastModifiedBy
 private String lastModifiedBy;}

 

 

전체 적용

@EntityListeners(AuditingEntityListener.class) 를 생략하고 스프링 데이터 JPA 가 제공하는
이벤트를 엔티티 전체에 적용하려면 orm.xml에 다음과 같이 등록하면 된다.

 

META-INF/orm.xml

<?xml version=“1.0” encoding="UTF-8”?>
<entity-mappings xmlns=“http://xmlns.jcp.org/xml/ns/persistence/orm”
 xmlns:xsi=“http://www.w3.org/2001/XMLSchema-instance”
 xsi:schemaLocation=“http://xmlns.jcp.org/xml/ns/persistence/
orm http://xmlns.jcp.org/xml/ns/persistence/orm_2_2.xsd”
 version=“2.2">
 <persistence-unit-metadata>
 <persistence-unit-defaults>
 <entity-listeners>
 <entity-listener 
class="org.springframework.data.jpa.domain.support.AuditingEntityListener”/>
 </entity-listeners>
 </persistence-unit-defaults>
 </persistence-unit-metadata>
 
</entity-mappings>

 

 

 

 

출처 : 김영한 JPA 스프링 데이터 강의

'JPA > JPA-Spring Data' 카테고리의 다른 글

Web 확장 - 페이징과 정렬  (0) 2022.07.22
Web 확장 - 도메인 클래스 컨버터  (0) 2022.07.22
사용자 정의 리포지토리 구현  (0) 2022.07.21
JPA Hint & Lock  (0) 2022.07.21
@EntityGraph  (0) 2022.07.21
복사했습니다!