반응형
Entity의 생성시간/수정시간 자동화
보통 entity에는 차후 유지보수를 위해 해당 데이터의 생성시간과 수정시간을 포함한다. 그래서 매번 DB에 해당 entity 데이터를 삽입/갱신 하기 전에 날짜 데이터를 등록/수정하는 코드가 중복되어 들어가게 된다.
public void save() {
...
image.setCreationDate(new LocalDateTime());
imageRepository.save(image);
...
}
이렇게 단순하고 반복적인 코드를 매번 적용하는 것은 매우 번거롭고 비효율적이다. JPA Auditing을 사용하면 이 문제를 간단하게 해결할 수 있다.
JPA Auditing 적용
BaseTimeEntity 생성
@Getter
@MappedSuperclass
@EntityListeners(AuditingEntityListener.class)
public abstract class BaseTimeEntity {
@CreatedDate
private LocalDateTime createdDate;
@LastModifiedDate
private LocalDateTime modifiedDate;
}
BaseTimeEntity 클래스는 모든 Entity 클래스의 상위 클래스가 되어 createdDate, modifiedDate 를 자동으로 관리하는 역할을 한다.
- @MappedSuperclass
- JPA Entity 클래스들이 BaseTimeEntity를 상속할 경우 createdDate, modifiedDate 도 column으로 인식하도록 한다.
- @EntityListeners(AuditingEntityListener.class)
- BaseTimeEntity에 Auditing 기능을 포함시킨다.
- @CreatedDate
- Entity가 생성되어 저장될 때 시간이 자동으로 저장된다.
- @LastModifiedDate
- 조회한 Entity의 값을 변경할 때 시간이 자동으로 저장된다.
BaseTimeEntity 상속
public class Image extends BaseTimeEntity {
...
}
JpaAuditing 설정
@EnableJpaAuditing
@SpringBootApplication
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
마지막으로 @EnableJpaAuditing 을 Application 클래스에 추가하여 JPA Auditing을 활성화하면 완성된다.
혹은 아래와 같이 class를 하나 생성하여 @Configuartion을 등록하고 거기에 @EnableJpaAuditing 를 추가하여 JPA Auditing을 활성화할 수 있다.
@Configuration
@EnableJpaAuditing
public class JpaConfig {}
마무리
이렇게 JPA auditing을 적용하면 DB에 데이터가 생성된 시간, 수정된 시간이 함께 저장되어 관리가 더 쉬워지게 된다.
반응형
'JPA' 카테고리의 다른 글
[Spring / JPA] Soft Delete를 JPA에서 적용하는 방법 (0) | 2024.05.21 |
---|---|
[Spring /JPA] Spring JPA Delete Query 작성 시 주의할 점 (0) | 2023.12.26 |
[JPA] 지연 로딩과 즉시 로딩 (0) | 2023.12.24 |
[JPA] JPA 연관 관계 정리 (0) | 2023.12.24 |
[JPA] Hibernate entity에 Lombok 사용 시 주의사항 (0) | 2023.12.24 |