🌱 이번 장의 스터디 범위
- JPA Auditing을 이용하여 등록/수정 시간을 자동화하는 방법
🌱 JPA Auditing으로 생성시간/수정시간 자동화하기
- 보통 엔티티에는 해당 데이터의 생성시간과 수정시간을 포함 : 차후 유지보수에 있어 중요한 정보
- 그러므로 DB에 삽입하기 전이나 갱신하기 전에 날짜 데이터를 등록/수정하는 코드가 필요
- 생성일 추가 코드 예제
public void savePosts() {
...
posts.setCreateDate(new LocalDate());
postsRepository.save(posts);
...
}
- 이런 코드가 모든 테이블과 서비스 메소드에 포함되면 코드가 지저분해지므로 JPA Auditing 사용
🌱 LocalDate을 사용해 JPA Auditing 자동화하기
- Java8부터 LocalDate와 LocalDateTime 등장
- 그 전에는 Date와 Canlendar 클래스가 있었으나 문제점이 있어 JodaTime 오픈소스를 사용했었음
- domain 패키지에 BaseTimeEntity 클래스 생성
// BaseTimeEntity.java
import lombok.Getter;
import org.springframework.data.annotation.CreatedDate;
import org.springframework.data.annotation.LastModifiedDate;
import org.springframework.data.jpa.domain.support.AuditingEntityListener;
import javax.persistence.EntityListeners;
import javax.persistence.MappedSuperclass;
import java.time.LocalDateTime;
@Getter
// JPA Entity 클래스들이 BaseTimeEntity를 상속할 경우 필드들(createdDate, modifiedDate)도 칼럼으로 인식하도록 함
@MappedSuperclass
// BaseTimeEntity 클래스에 Auditing 기능을 포함시킴
@EntityListeners(AuditingEntityListener.class)
public class BaseTimeEntity {
// Entity가 생성되어 저장될 때 시간이 자동 저장
@CreatedDate
private LocalDateTime createdDate;
// 조회한 Entity의 값을 변경할 때 시간이 자동 저장
@LastModifiedDate
private LocalDateTime modifiedDate;
}
- Posts 클래스가 BaseTimeEntity를 상속받도록 코드 변경
// Posts.java
public class Posts extends BaseTimeEntity {
...
}
- JPA Auditing 어노테이션들을 모두 활성화할 수 있도록 Application 클래스에 활성화 어노테이션 하나 추가
// Application.java
@EnableJpaAuditing // JPA Auditing 활성화
@SpringBootApplication
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
🌱 JPA Auditing 테스트 코드 작성하기
- PostsRepositoryTest 클래스 코드에 테스트 메소드 하나 추가
// PostsRepositoryTest.java
@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.getCreatedDate()+", modifiedDate="+posts.getModifiedDate());
assertThat(posts.getCreatedDate()).isAfter(now);
assertThat(posts.getModifiedDate()).isAfter(now);
}
- JPA Auditing 테스트 코드 결과
- 앞으로 추가될 엔티티들은 등록일/수정일 고민할 필요없이 BaseTimeEntity만 상속받으면 자동으로 해결
'Java-Spring > 스프링 부트와 AWS로 혼자 구현하는 웹 서비스' 카테고리의 다른 글
[Spring Boot] 04장. 머스테치로 화면 구성하기 - 서버 템플릿 엔진과 머스테치 소개 (0) | 2021.10.11 |
---|---|
[Spring Boot] Spring 웹계층 (0) | 2021.10.06 |
[Spring Boot] 03장. 스프링 부트에서 JPA로 데이터베이스 다뤄보자 - JPA (0) | 2021.10.04 |
[Spring Boot] 02장. 스프링 부트에서 테스트 코드를 작성하자 (0) | 2021.10.02 |
[Spring Boot] 01장. 인텔리제이로 스프링 부트 시작하기 (0) | 2021.10.02 |