보통 Entity에는 해당 데이터의 수정시간과 생성시간을 포함한다.
언제 만들어지고 수정되었는지는 차후 유지보수에 있어서 매우 중요한 정보이다
- 매번 DB에 삽입 전, 갱신 전에 날짜 데이터를 등록/수정하는 코드가 여기저기 들어가면 귀찮고 코드가 지저분 해짐.
- 이를 해결하고자 JPA Auditing을 사용
1. JPA Auditing
Auditing을 사용하면 Entity를 누가 언제 생성/수정했는지 자동으로 기록하게 할 수 있다.
2. JPA Auditing 적용하기
1) BaseTimeEntity.java
@Getter
@MappedSuperclass
@EntityListeners(AuditingEntityListener.class)
public class BaseTimeEntity {
@CreatedDate
private LocalDateTime createdDate;
@LastModifiedDate
private LocalDateTime modifiedDate;
}
(1) @MappedSupperclass
JPA Entity 클래스들이 BaseTimeEntity를 상속할 경우 필드들(createdDate, modifiedDate)도 칼럼으로 인식하도록 함.
(2) @EntityListener(AuditingEntityListener.class)
BaseTimeEntity 클래스에 Auditing 기능을 포함시킨다.
(3) @CreatedDate
Entity가 생성되어 저장될 때 시간이 자동 저장된다.
(4) @LastModifiedDate
조회한 Entity 값을 변경할 때 시간이 자동 저장된다.
2) Posts 클래스가 BaseTimeEntity를 상속받도록 변경
public class Posts extends BaseTimeEntity {
...
}
3) Application 클래스에 활성화 어노테이션 추가
@EnableJpaAuditing
@SpringBootApplication
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
- JPA Audtiting 어노테이션들을 모두 활성화 할 수 있도록 함
앞으로 추가될 엔티티들은 더이상 등록/수정일로 고민할 필요가 없다.
BaseTimeEntity만 상속받으면 자동으로 해결된다 !
3. JPA Auditing Test Code
- PostRepositoryTest.java
@Test
public void BaseTimeEntity_create(){
LocalDateTime now = LocalDateTime.of(2024,1,11,21,39,0);
postsRepository.save(Posts.builder()
.title("title")
.content("content")
.author("author")
.build());
List<Posts> postsList = postsRepository.findAll();
Posts posts = postsList.get(0);
System.out.println(">>> createDate = "+posts.getCreatedDate()+", modifiedDate="+posts.getModifiedDate());
assertThat(posts.getCreatedDate()).isAfter(now);
assertThat(posts.getModifiedDate()).isAfter(now);
}
'스프링부트와 AWS로 혼자 구현하는 웹서비스' 카테고리의 다른 글
Part 9. 게시글 화면 만들기 (2) (0) | 2024.01.13 |
---|---|
Part 8. 게시글 화면 만들기 (1) (2) | 2024.01.13 |
Part 6. 등록/수정/조회 API 만들기 (0) | 2023.12.17 |
Part5. 프로젝트에 Spring Data JPA 적용 (0) | 2023.12.14 |
Part 4. JPA (0) | 2023.12.08 |