* 책 스프링 부트와 AWS로 혼자 구현하는 웹 서비스의 내용을 담고 있습니다.
엔티티에는 해당 데이터의 생성시간, 수정시간을 포함한다.
이와 관련된 코드가 여기저기 들어가야하기 때문에 JPA Auditing을 사용한다!
(Java8부터 LocalDate와 LocalDateTime이 등장)
📍 domain 패키지에 BaseTimeEntity 클래스를 생성
BaseTimeEntity 클래스는 모든 Entity의 상위 클래스가 되어 Entity들의 createdAt, updatedAt을 자동으로 관리하는 역할이다.
@Getter
@MappedSuperclass
@EntityListeners(AuditingEntityListener.class)
public abstract class BaseTimeEntity {
@CreatedDate
private LocalDateTime createdAt;
@LastModifiedDate
private LocalDateTime updatedAt;
}
✅ @MappedSuperclass
JPA Entity 클래스들이 BaseTimeEntity를 상속할 경우 필드들(createdAt, updatedAt)도 column으로 인식하도록 한다.
✅ @EntityListeners(AuditingEntityListener.class)
BaseTimeEntity 클래스에 Auditing 기능을 포함시킨다.
✅ @CreatedDate
Entity가 생성되어 저장될 때 시간이 자동 저장된다.
✅ @LastModifiedDate
조회된 Entity의 값을 변경할 때 시간이 자동 저장된다.
📍 다른 domain 클래스들에서 BaseTimeEntity를 상속받도록 변경한다.
...
public class PlantLog extends BaseTimeEntity {
...
}
📍 마지막으로 JPA Auditing 어노테이션들을 모두 활성화할 수 있도록 Application 클래스에 활성화 어노테이션 하나를 추가한다.
@EnableJpaAuditing
@SpringBootApplication
public class ServerApplication {
...
}
✅ @EnableJpaAuditing
JPA Auditing 활성화
'Backend > 프로젝트' 카테고리의 다른 글
[SpringBoot JPA] JSON으로 LocalDate 통신하는 방법 (0) | 2022.08.25 |
---|---|
[SpringBoot JPA] BaseResponseMessage 작성하기 (0) | 2022.08.17 |
[SpringBoot JPA] 서버 무중단 배포를 하는 이유는? (0) | 2022.08.17 |
[SpringBoot JPA] 엔티티 연관관계 매핑 완료, Web server failed to start. Port 8080 was already in use. 오류 해결 (0) | 2022.08.15 |
[SpringBoot JPA & AWS] datagrip으로 DB 연결 확인하기 (0) | 2022.08.14 |