JPA Auditing 생성시간/수정시간 자동화

Daniel6364·2022년 7월 29일
0

JPA Auditing

  • 보통 Entity에는 해당 데이터의 생성시간과 수정시간을 포함한다.
  • 그렇다 보니 매번 DB에 insert하기 전, update하기 전에 날짜 데이터를 등록/수정하는 코드가 여기저기 들어가게 된다.
  • 이런 단순하고 반복적인 코드가 모든 테이블과 서비스 메서드에 포함되는 것은 귀찮고 코드가 지저분해 진다.
  • JPA Auditing으로 해결 가능?하다.

LocalDate 사용

  • Java8부터 LocalDate와 LocalDateTime이 등장
  • 기존에 Date의 문제점을 보완한 타입이기 때문에 Java8인경우 무조건 사용해야 함.

    참고

    기존 Date와 Calendar 클래스의 문제점

    1. 불변(변경이 불가능한) 객체가 아님
      • 멀티스레드 환경에서 언제든 문제가 발생할 수 있음
    2. Calendar의 Month 값 설계 오류
      • 10월 : Calendar.OCTOBER의 값이 '9'로 표기

예제

  1. BaseTimeEntity 클래스 생성
    • abstract class임에 유의하자.
@Getter
@MappedSuperclass // JPA Entity 클래스들이 BaseTimeEntity를 상속할 경우 필드들(createDate, modifiedDate)도 칼럼으로 인식하도록 합니다.
@EntityListeners(AuditingEntityListener.class) // BaseTimeEntity 클래스에 Auditing 기능을 포함시킵니다.
public abstract class BaseTimeEntity {

    @CreatedDate // 생성 시간
    private LocalDateTime createdDate;

    @LastModifiedDate // 수정 시간
    private LocalDateTime modifiedDate;
}
  1. 상속처리
public class Posts extends BaseTimeEntity {
	//...    
  1. Application 클래스에 어노테이션 추가
@EnableJpaAuditing // JPA Auditing 활성화
@SpringBootApplication
public class AwsJpaApplication {

	public static void main(String[] args) {
		SpringApplication.run(AwsJpaApplication.class, args);
	}
}
  1. JPA Auditing 테스트 코드 작성
@Test
    public void baseTimeEntity() {

        LocalDateTime dateTime = LocalDateTime.of(2022, 7, 29, 0, 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("1. ==> createDate : " + posts.getCreatedDate());
        System.out.println("2. ==> modifiedDate : " + posts.getModifiedDate());

        assertThat(posts.getCreatedDate()).isAfter(dateTime);
        assertThat(posts.getModifiedDate()).isAfter(dateTime);
    }
  1. 테스트 결과 console 확인
Hibernate: 
    insert 
    into
        posts
        (created_date, modified_date, author, content, title) 
    values
        (?, ?, ?, ?, ?)
Hibernate: 
    select
        posts0_.id as id1_0_,
        posts0_.created_date as created_2_0_,
        posts0_.modified_date as modified3_0_,
        posts0_.author as author4_0_,
        posts0_.content as content5_0_,
        posts0_.title as title6_0_ 
    from
        posts posts0_
1. ==> createDate : 2022-07-29T16:24:23.696123
2. ==> modifiedDate : 2022-07-29T16:24:23.696123
Hibernate: 
    select
        posts0_.id as id1_0_,
        posts0_.created_date as created_2_0_,
        posts0_.modified_date as modified3_0_,
        posts0_.author as author4_0_,
        posts0_.content as content5_0_,
        posts0_.title as title6_0_ 
    from
        posts posts0_
Hibernate: 
    delete 
    from
        posts 
    where
        id=?
profile
The Office Lover

0개의 댓글