JPA Auditing 적용기

Bong2·2024년 7월 13일

Spring

목록 보기
7/9

JPA Auditing이란?

엔티티의 생성 및 수정 시점을 자동으로 기록하고 관리하는 기능을 제공하는 도구

이전에는 각 Entity들에게 생성 및 수정 시점들을 각각 작성했었다. 그래서 유지보수에서는 비효율적이다.
근데 Spring Data JPA에서는 시간에 대해서 자동으로 값을 넣어주는 기능인 Auditing이 있다.

사용방법

추상클래스 생성

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

    @CreatedDate
    @Column(updatable = false)
    @Temporal(TemporalType.TIMESTAMP)
    private LocalDateTime createdAt;

    @LastModifiedDate
    @Column
    @Temporal(TemporalType.TIMESTAMP)
    private LocalDateTime modifiedAt;
}
  • @MappedSuperclass : 해당 추상 클래스를 상속하면 createdAt, modifitedAt의 변수를 사용할 수 있다.
  • @EntityListeners : 해당 클래스에서 Auditing기능을 추가해준다.
  • @CreatedDate: 엔티티가 처음 생성될 때의 타임스탬프를 자동으로 기록합니다.
    1. 최초 생성 시간이 저장되고 그 이후에는 수정되면 안되기 때문에 updatable = false 옵션을 추가
  • @LastModifiedDate: 엔티티가 마지막으로 수정될 때의 타임스탬프를 자동으로 기록합니다
  • @Temporal : 날짜 타입에 매핑할 때 사용, 3가지 타입이 존재
    • DATE : ex) 2023-01-01
    • TIME : ex) 20:21:14
    • TIMESTAMP : ex) 2023-01-01 20:22:38.771000

springApplication에 추가

@EnableJpaAuditing
@SpringBootApplication
public class PreparingSpringApplication {

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

}
  • @EnableJpaAuditing : JPA Auditing 사용하기위한 설정

Entity

public class Memo extends Timestamped

추상클래스를 상속받아서 사용하면 Entity별로 변경을 하거나 추가하지 않아도 된다.

예시


위와 같은 그림으로 DB에 저장되는 것을 확인할 수 있다.

profile
자바 백엔드 개발자로 성장하자

0개의 댓글