보통 엔티티에 해당 데이터의 생성시간과 수정시간이 공통적으로 포함된다. 그래서 이들 공통 코드를 모듈화시키겠다.
자바 8부터는 LocalDate 클래스를 사용하자. 기존의 Date나 Calenter 클래스가 갖고 있는 문제(불변성, 월값 설계 오류) 를 고친 버전이다.
@CreationTimestamp
private Timestamp createDate; //이거 말고
도메인 패키지에 BaseTimeEntity를 생성.
@Getter
@MappedSuperclass //JPA Entity 클래스들이 이 클래스를 상속받을 경우, 필드들도 칼럼으로 인식
@EntityListeners(AuditingEntityListener.class) //Auditing 기능포함
public abstract class BaseTimeEntity {
@CreatedDate
private LocalDateTime createDate;
@LastModifiedDate
private LocalDateTime modifiedDate;
}
@EnableJpaAuditing
@SpringBootApplication
public class IntellijStartApplication {
public static void main(String[] args) {
SpringApplication.run(IntellijStartApplication.class, args);
}
}
public class Posts extends BaseTimeEntity
https://webcoding-start.tistory.com/53
@Test
public void BaseTimeEntity_등록() {
//given
LocalDateTime now = LocalDateTime.of(2019, 6, 4, 0, 0, 0);
postsRepository.save(Posts.builder()
.title("title")
.content("content")
.author("author")
.build());
//when
List<Posts> postsList = postsRepository.findAll();
//then
Posts posts = postsList.get(0);
System.out.println(">>>>>>>>> createDate=" + posts.getCreateDate() + ", modifiedDate=" + posts.getModifiedDate());
assertThat(posts.getCreateDate()).isAfter(now);
assertThat(posts.getModifiedDate()).isAfter(now);
}