JPA Auditing
Spring Data JPA 에서는 자동으로 엔티티를 생성하거나 변경할 때마다 자동으로 넣어주는 기능을 제공하는 JPA Auditing에 대해 알아보겠습니다.
JPA Auditing이란?
- JPA에서 'Audit'는 '감시하다' 라는 뜻으로, 각 데이터마다 '누가', '언제' 데이터를 생성했고 변경했는지 감시한다는 의미로 사용된다.
- 엔티티 클래스에 공통적으로 들어가는 필드가 있다.
- 생성 주체
- 생성 일자
- 변경 주체
- 변경 일자
JPA Auditing 기능 활성화
@EnableJPAAuditing 추가
@SpringBootApplication
@EnableJpaAuditing
public class AdvancedJpaApplication {
public static void main(String[] args) {
SpringApplication.run(AdvancedJpaApplication.class, args);
}
}
- 스프링부트 애플리케이션에 Auditing 기능을 활성화해야한다.
- @EnableJpaAuditing 어노테이션을 추가한다.
Configuration 추가
@Configuration
@EnableJpaAuditing
public class JpaAuditingConfiguration {
}
- 테스트 코드를 작성해서 애플리케이션을 테스트하는 상황에 오류가 발생할 수 있다.
- 해당 문제를 해결하기 위해 Configuration 클래스를 생성하여 애플리케이션 클래스의 기능과 분리하여 활성화할 수 있다.
- 애플리케이션 클래스의 어노테이션을 지워야 정상적으로 동작한다.
BaseEntity 생성
- 코드의 중복을 없애기 위하여 각 엔티티에 공통으로 들어가는 컬럼(필드)을 하나의 클래스로 빼는 작업을 수행해야한다.
- 생성일자와 생성변경일자만 추가해서 생성한다
@Getter
@Setter
@ToString
@MappedSuperclass
@EntityListeners(AuditingEntityListener.class)
public class BaseEntity {
@CreatedDate
@Column(updatable = false)
private LocalDateTime createdAt;
@LastModifiedDate
private LocalDateTime updatedAt;
}
- 사용한 주요 어노테이션
- @MappedSuperclass : JPA 엔티티 클래스가 상속받을 경우 자식 클래스에게 매핑 정보를 전달한다.
- @EntityListeners : 엔티티를 데이터베이스에 적용하기 전 후로 콜백을 요청할 수 있게 하는 어노테이션이다.
- AuditingEntityLister : 엔티티의 Auditing 정보를 주입하는 JPA 엔티티 리스너 클래스이다.
- @CreateDate : 데이터 생성 날짜를 자동으로 주입하는 어노테이션이다.
- @LastModifiedDate : 데이터 수정 날짜를 자동으로 주입하는 어노테이션이다.
BaseEntity를 상속받은 Product 엔티티 클래스
@Getter
@Setter
@Entity
@NoArgsConstructor
@AllArgsConstructor
@Builder
@EqualsAndHashCode(callSuper = true)
@ToString(callSuper = true)
@Table(name = "product")
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;
}
- @ToStirng, @EqualsAndHashCode 어노테이션에 적용한 callSuper 속성은 부모 클래스의 필드를 포함하는 역할을 수행한다.
- LocalDateTime.now( ) 메서드를 사용하여 시간을 주입하지 않아도 자동으로 값이 생성된다.
JPA Auditing 테스트
@SpringBootTest
class JpaAuditingConfigurationTest {
@Autowired
ProductRepository productRepository;
@Test
void auditingTest() {
Product product = Product.builder()
.name("pen")
.price(1000)
.stock(100)
.build();
Product saved = this.productRepository.save(product);
System.out.println("productName : " + product.getName());
System.out.println("CreatedAt : " + product.getCreatedAt());
}
}
JPA Auditing 테스트 결과
- 직접 날짜를 기입하지 않았지만 정상적으로 데이터베이스에는 생성일자가 저장
- 엔티티의 필드를 출력하면 해당 시간이 출력되는 것을 확인할 수 있다.
반응형
'Book > 스프링부트 핵심가이드' 카테고리의 다른 글
연관관계 매핑 (of. 일대일(1:1) 매핑) (0) | 2023.11.14 |
---|---|
@Query 어노테이션 관련 내용 정리 (2) | 2023.11.09 |
정렬과 페이징 처리 방법과 예시 (1) | 2023.11.09 |
댓글