본문 바로가기

Spring Data JPA

Auditing

 

실전! 스프링 데이터 JPA - 인프런 | 강의

스프링 데이터 JPA는 기존의 한계를 넘어 마치 마법처럼 리포지토리에 구현 클래스 없이 인터페이스만으로 개발을 완료할 수 있습니다. 그리고 반복 개발해온 기본 CRUD 기능도 모두 제공합니다.

www.inflearn.com

 

Spring Data JPA - Reference Documentation

Example 119. Using @Transactional at query methods @Transactional(readOnly = true) interface UserRepository extends JpaRepository { List findByLastname(String lastname); @Modifying @Transactional @Query("delete from User u where u.active = false") void del

docs.spring.io

 

Auditing

관계형 데터베이스의 테이블에는 도메인들이 공통적으로 가지고 있는 필드나 컬럼들이 존재한다.

대표적으로 생성일자, 수정일자, 식별자 같은 필드 및 컬럼들이 있으며 Spring Data는 엔티티를 생성하거나 변경할 때 이러한 값들을 자동으로 넣어주는 Auditing 기능을 제공한다.

 

먼저 아래와 같이 스프링 부트의 Application.class에서 @EnableJpaAuditing 어노테이션을 설정하여 기능을 활성화 할 수 있다.

@SpringBootApplication
@EnableJpaAuditing
public class BbsApplication {
   public static void main(String[] args) {
      SpringApplication.run(BbsApplication.class, args);
   }
}

 

어노테이션 소개

Auditing 기능에서는 아래와 같은 어노테이션들을 사용하게 된다.

  • @MappedSupperClass
    - JPA Entity 클래스에서 해당 어노테이션이 선언된 추상클래스를 상속받는 경우 추상클래스의 필드를 컬럼으로 인식한다.
  • @EntityListeners(AuditingEntityListener.class)
    - @EntityListeners는 엔티티를 DB에 반영하기 전, 후 시점에 커스텀 콜백을 적용하는 어노테이션이다.
    - AuditingEntityListener.class 를 인자로 넘기면 Auditing 기능을 수행하게 된다.
  • @CreatedDate, @LastModifiedDate
    - 엔티티를 생성, 수정 한 시점의 일시를 자동으로 삽입하여준다.
  • @CreatedBy, @LastModifedBy
    - 엔티티를 생성, 수정한 사용자를 자동으로 삽입하여준다.
    - 해당 기능은 AuditorAware 객체를 구현하여 사용자 정보를 반환시켜줘야한다.
    - Spring Security의 Authentication 기능과 함께 사용하여야 하므로 이번 포스팅에서는 다루지 않는다.

 

구현방법

1. @MappedSuperclass와 @EntityListeners(AuditingEntityListener.class) 어노테이션을 사용하여
    JPA 엔티티에 공통적으로 적용할 Auditing 추상클래스를 구현한다.

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

    @CreatedDate
    @Column(updatable = false)
    private LocalDateTime createdAt;

    @LastModifiedDate
    @Column(updatable = false)
    private LocalDateTime updatedAt;
}

 

 

2. JPA 엔티티 클래스에서 구현한 Auditing 추상 클래스를 상속받는다.

@Entity
public class Member extends BaseEntity{
    
    @Id
    @GeneratedValue
    private Long id;
    
    private String username;
}​