JPA를 사용할 때 생성자, 수정자, 생성일, 수정일 등 도메인들이 공통적으로 가지고 있는 속성이 있다면 JPA Auditing 기능 을 사용하는 것을 고려해볼 수 있습니다. 공통적인 속성이 있다는 것은 반복되는 코드가 생긴다는 것인데 JPA에서는 이 문제를 Auditing 기능을 통해 해결해줍니다.
Auditing 사용 예제
1. build.gradle에 의존성 추가
implementation 'org.springframework.boot:spring-boot-starter-data-jpa'
2. Application Main 클래스에 @EnableJpaAuditing 어노테이션 추가
@SpringBootApplication
@EnableJpaAuditing
public class HarmonicElliotTradingHelperApplication {
public static void main(String[] args) {
SpringApplication.run(HarmonicElliotTradingHelperApplication.class, args);
}
}
3. 공통 속성을 관리하는 Entity 클래스
@EntityListeners(AuditingEntityListener.class)
@MappedSuperclass
@Getter
public class BaseTimeEntity {
@CreatedDate
@Column(name="created", updatable = false)
private LocalDateTime createdDate;
@LastModifiedDate
private LocalDateTime lastModifiedDate;
}
- @EntityListener(AuditingEntityListener.class) = 엔티티의 변화를 감지할 수 있는 Annotation
- @MappedSuperclass = 공통 매핑 속성을 필요할 때 사용하며 부모로부터 속성 정보만 사용. 실제 DB의 관계가 부모 자식 관계로 되는 것은 아님.
- @CreateDate = 엔티티를 저장하면 생성일이 자동으로 설정
- @LastModifedDate = 엔티티를 변경하면 변경일이 자동으로 설정. 엔티티 저장 시 Default는 생성일과 같음
4. 테스트
@Test
@DisplayName("생성날짜, 수정날짜 Auditing 테스트")
public void creatAndUpdateTest() throws InterruptedException {
WaveMaster wm = new WaveMaster();
em.persist(wm);
em.flush();
em.clear();
/**
* 생성날짜, 수정날짜 설정확인
*/
WaveMaster findWm1 = em.find(WaveMaster.class, wm.getId());
assertNotNull(findWm1.getCreatedDate());
assertNotNull(findWm1.getLastModifiedDate());
System.out.println("findWm1.getCreatedDate() = " + findWm1.getCreatedDate());
System.out.println("findWm1.getLastModifiedDate() = " + findWm1.getLastModifiedDate());
assertTrue(findWm1.getCreatedDate().equals(findWm1.getLastModifiedDate()));
/**
* 속성 변경 후 수정날짜 확인
*/
Thread.sleep(1000);
findWm1.setDirection(Direction.SIDE_TREND);
em.flush();
em.clear();
WaveMaster findWm2 = em.find(WaveMaster.class, wm.getId());
System.out.println("findWm2.getCreatedDate() = " + findWm2.getCreatedDate());
System.out.println("findWm2.getLastModifiedDate() = " + findWm2.getLastModifiedDate());
assertTrue(wm.getCreatedDate().compareTo(findWm2.getLastModifiedDate()) == -1);
}
- WaveMaster란 엔티티를 생성한 후 persist() 메소드를 실행하면서 영속성 컨텍스트에 저장
- 조회했을 때 생성일, 수정일이 정상적으로 설정 되었는지 확인
- Direction 속성을 변경한 후 영속성 컨텍스트의 값을 DB에 반영
- 수정일이 정상적으로 변경되었는지 확인
'Spring > JPA & Querydsl' 카테고리의 다른 글
[Querydsl] Springboot 3.0에서 Querydsl 설정하기 (0) | 2023.03.21 |
---|