스프링 부트로 구현하는 웹서비스 - 8 Local Date

Bumgu·2023년 7월 16일
0
@Getter  
@MappedSuperclass  
@EntityListeners(AuditingEntityListener.class)
public class BaseTimeEntity {  
  
@CreatedDate  
private LocalDateTime createdDate;  
  
@LastModifiedDate  
private LocalDateTime modifiedDate;  
}

@MappedSuperclass

  • JPA Entity 클래스들이 BaseTimeEntity를 상속할 경우 필드들도 칼럼으로 인식하도록 함.

@EntityListeners(AuditingEntityListener.class)

  • BaseTimeEntity클래스에 Auditing 기능을 포함시킴.

@CreatedDate

  • Entity가 생성되어 저장될 때 시간이 자동 저장됨.

@LastModifedDate

  • 조회한 Entity의 값을 변경할 때 시간이 자동 저장됨.

Posts.java

@Getter  
@NoArgsConstructor  
@Entity  
public class Posts extends BaseTimeEntity {
// BaseTimeEntity를 상속

Application.java

@EnableJpaAuditing //JPA Auditing 활성화  
@SpringBootApplication  
public class Application {  
  
public static void main(String[] args) {  
SpringApplication.run(Application.class, args);  
}  
}

JPA Auditing 테스트

@Test  
public void BaseTimeEntity_등록() {  
//given  
LocalDateTime now = LocalDateTime.of(2023, 7, 14, 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.getCreatedDate() + ", modifedDate =" + posts.getModifiedDate());  
  
assertThat(posts.getCreatedDate()).isAfter(now);  
assertThat(posts.getModifiedDate()).isAfter(now);  
}

테스트를 실행해보면..

이렇게 생성이된다.

앞으로 추가되는 Entity는 더이상 등록/수정일을 고민할 필요가 없다.
BaseTimeEntity만 상속받으면 된다.

profile
Software VS Me

1개의 댓글

comment-user-thumbnail
2023년 7월 17일

저도 개발자인데 같이 교류 많이 해봐요 ㅎㅎ! 서로 화이팅합시다!

답글 달기