Blog

[Spring-LDW] Timestamp용도의 클래스 생성 및 JPA Auditing 설정

Category
Author
citeFred
citeFred
PinOnMain
1 more property
스프링 부트와 AWS로 혼자 구현하는 웹 서비스  : 인텔리제이, JPA, JUnit 테스트, 그레이들, 소셜 로그인, AWS 인프라로 무중단 배포까지 이동욱 저
Java에서 ORM 기술인 JPA를 사용하여 도메인을 관계형 데이터베이스 테이블에 매핑할 때 공통적으로 도메인들이 가지고 있는 필드나 컬럼들이 존재합니다. 대표적으로 생성일자, 수정일자, 식별자 같은 필드 및 컬럼이 있습니다.
Table of Content

JPA Auditing의 필요성?

데이터베이스에서 누가, 언제하였는지 기록을 잘 남겨놓아야 합니다. 그렇기 때문에 생성일, 수정일 컬럼은 대단히 중요한 데이터 입니다.
그래서 JPA에서는 Audit이라는 기능을 제공하고 있습니다. Audit은 감시하다, 감사하다라는 뜻으로 Spring Data JPA에서 시간에 대해서 자동으로 값을 넣어주는 기능입니다.
참고로 자바 1.8 이상부터는 기존의 문제가 있던 Date, Calander 클래스를 사용하지 않고 LocalDate, LocalDateTime 클래스를 사용합니다. 또한 LocalDateTime 객체와 테이블 사이의 매핑이 안되던 이슈는 하이버네이트 5.2 버전부터 해결이 되었습니다.

게시글에 타임스탬프 기능 추가하기

BaseTimeEntity.java

package com.citefred.ldwspring.domain; import jakarta.persistence.EntityListeners; import jakarta.persistence.MappedSuperclass; import lombok.Getter; import org.springframework.data.annotation.CreatedDate; import org.springframework.data.annotation.LastModifiedDate; import org.springframework.data.jpa.domain.support.AuditingEntityListener; import java.time.LocalDateTime; @Getter @MappedSuperclass @EntityListeners(AuditingEntityListener.class) public abstract class BaseTimeEntity { @CreatedDate private LocalDateTime createdDate; @LastModifiedDate private LocalDateTime modifiedDate; }
Java
복사

@MappedSuperclass

JPA Entity 클래스들이 BaseTimeEntity 클래스를 상속할 경우 필드들(createdDate, modifiedDate)도 컬럼으로 인식하도록 합니다.

@EntityListeners(AuditingEntityListener.class)

BaseTimeEntity 클래스에 JPA Auditing 기능을 포함시킵니다.

@CreatedDate

Entity가 생성되어 저장될 때 시간이 자동 저장됩니다.(System)

@LastModifiedDate

조회한 Entity의 값을 변경 할 때 (더티체킹 수정) 시간이 자동 저장 됩니다.(System)

Posts.java

Posts 클래스가 BaseTimeEntity 클래스를 상속 받도록 합니다.
package com.citefred.ldwspring.domain.posts; import com.citefred.ldwspring.domain.BaseTimeEntity; import jakarta.persistence.*; import lombok.Builder; import lombok.Getter; import lombok.NoArgsConstructor; @Getter @NoArgsConstructor @Entity public class Posts extends BaseTimeEntity { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Long id; ... } }
Java
복사
extends를 통해 간단히 클래스를 상속 받으면 Posts 클래스는 createdDate, modifiedDate 필드를 가진 상태(Java 문법에 따라 클래스 상속관계에 따라 부모 클래스의 필드를 기본으로 가짐)가 됩니다.

타임스탬프 기능 테스트 코드

PostsRepositoryTest.java

package com.citefred.ldwspring.domain.posts; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.test.context.junit.jupiter.SpringExtension; import java.time.LocalDateTime; import java.util.List; import static org.assertj.core.api.Assertions.assertThat; @ExtendWith(SpringExtension.class) @SpringBootTest public class PostsRepositoryTest { @Autowired PostsRepository postsRepository; //@After @AfterEach public void cleanup(){ postsRepository.deleteAll(); } ... @Test public void BaseTimeEntity_등록(){ //given LocalDateTime now = LocalDateTime.of(2023,12,23,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); } }
Java
복사

.isAfter(now);

시점을 기준으로 이후 or isBefore는 이전 을 검증하는 메소드

format - LocalDateTime의 출력형식을 변환하고 싶은 경우

현재 날짜의 형식은 2023-12-23T22:17:17.103591 와 같이 알아보기 어렵게 나타나고 경우에 따라 날짜만 필요하거나 ms등이 필요 없을 수도 있다. 이런 경우 DateTimeFormatter.ofPattern() 클래스의 메소드를 통해 출력형식을 변환 할 수 있다.
//DateFormat 변경하는 경우 1 String localDateTimeFormat1 = now.format(DateTimeFormatter.ofPattern("yyyyMMddHHmmssSSS")); //DateFormat 변경하는 경우 2 String localDateTimeFormat2 = now.format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss:SSS") ); ... System.out.println(localDateTimeFormat1);//DateFormat 변경 확인1 System.out.println(localDateTimeFormat2);//DateFormat 변경 확인2
Java
복사
이처럼 원하는 양식을 지정하면
1번 : 20231223000000000 2번 : 2023-12-23 00:00:00:000
처럼 출력 양식을 원하는대로 수정 할 수 있다.
Search
 | Main Page | Category |  Tags | About Me | Contact | Portfolio