JPA Auditing 적용

코딩하는 하늘토끼·2023년 6월 22일

스프링부트 공부

목록 보기
15/15

JPA Auditing이란?
엔티티가 생성되고, 변경되는 그 시점을 감지하여 생성시각, 수정시각, 생성한 사람, 수정한 사람을 기록하는 기능

JPA Auditing 기능 활성화

코드

config/JpaAuditingConfiguration.java

package com.springboot.hello.config;

import org.springframework.context.annotation.Configuration;
import org.springframework.data.jpa.repository.config.EnableJpaAuditing;

@Configuration
@EnableJpaAuditing  //HelloApplication.java 에서 사용해도 되지만 @WebMvcTest 같은 테스트 코드에서 예외가 발생할 수 있음
public class JpaAuditingConfiguration {
    
}

BaseEntity 만들기

코드

data/entity/BaseEntity.java

package com.springboot.hello.data.entity;

import jakarta.persistence.Column;
import jakarta.persistence.EntityListeners;
import jakarta.persistence.MappedSuperclass;
import lombok.Getter;
import lombok.Setter;
import lombok.ToString;
import org.springframework.data.annotation.CreatedDate;
import org.springframework.data.annotation.LastModifiedDate;
import org.springframework.data.jpa.domain.support.AuditingEntityListener;

import java.time.LocalDateTime;

@Getter
@Setter
@ToString
@MappedSuperclass   // JPA의 엔티티 클래스가 상속받을 경우 자식 클래스에게 매핑 정보를 전달
@EntityListeners(AuditingEntityListener.class)  // 엔티티를 데이터베이스에 적용하기 전후로 콜백을 요청할 수 있게 하는 어노테이션
public class BaseEntity {

    @CreatedDate    // 데이터 생성 날짜 자동 주입 어노테이션
    @Column(updatable = false)
    private LocalDateTime createdAt;

    @LastModifiedDate   // 데이터 수정 날짜 자동 주입 어노테이션
    private LocalDateTime updatedAt;

}

data/entity/Product.java

package com.springboot.hello.data.entity;

import jakarta.persistence.*;
import lombok.Getter;
import lombok.Setter;

import java.time.LocalDateTime;

@Entity // 해당 클래스가 엔티티임을 명시(* 필수)
@Table(name = "product")    //DB Table 이름 지정(생략 가능, 생략시 클래스 이름으로 생성)
@Getter //Lombok Getter 메소드 자동 생성(편의성)
@Setter //Lombok Setter 메소드 자동 생성(편의성)
public class Product extends BaseEntity {

    @Id //테이블 기본키 지정
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long number;

    @Column(nullable = false)   //테이블 컬럼 지정(별다른 설정 없을 시 생략 가능)
    private String name;

    @Column(nullable = false)
    private Integer price;

    @Column(nullable = false)
    private Integer stock;

    //@Transient    //데이터베이스에서 필요 없을 경우 사용하는 어노테이션

}

테스트

코드

test/data/entity/JpaAuditingTest.java

package com.springboot.hello.data.entity;

import com.springboot.hello.data.repository.ProductRepository;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;

@SpringBootTest
public class JpaAuditingTest {

    @Autowired
    public ProductRepository productRepository;

    @Test
    public void auditingTest() {

        Product product = new Product();
        product.setName("펜");
        product.setPrice(1000);
        product.setStock(123);

        Product savedProduct = productRepository.save(product);

        System.out.println(savedProduct.getName());
        System.out.println(savedProduct.getCreatedAt());

    }
}

실행 결과

0개의 댓글