WORK/STUDY

[Spring] JPA Auditing(생성/수정시간 자동화)

Justin Mendes 2023. 10. 26. 21:43
 

스프링 부트와 AWS로 혼자 구현하는 웹 서비스 - 예스24

가장 빠르고 쉽게 웹 서비스의 모든 과정을 경험한다. 경험이 실력이 되는 순간!이 책은 제목 그대로 스프링 부트와 AWS로 웹 서비스를 구현한다. JPA와 JUnit 테스트, 그레이들, 머스테치, 스프링

www.yes24.com

*위의 책을 따라 학습한 것을 정리한 내용입니다


사용이유

보통 entity에는 언제 만들어졌는지, 언제 수정됐는지 등 유지보수를 위해 데이터의 생성/수정시간을 포함해야한다.

DB에 삽입 전, 갱신 전 날짜 데이터를 등록/수정하는 코드가 여기저기 들어가게 되는 단순하고 반복적인 코드를 매번 작성하는게 번거롭고 코드가 지저분해진다.

이를 해결하기 위한 것이 JPA Auditing이다.

 

예제

com.study.springboot.domain패키지에 BaseTimeEntity.java 생성

@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가 생성되어 저장 시간 자동 저장

 

@LastModifiedDate

- 조회한 Entity 값 변경 시 시간 자동 저장

 

 

domain.posts 안의 Posts BaseTimeEntity 상속시키게 한다.

public class Posts extends BaseTimeEntity{ ... }

Application.java에 어노테이션을 하나 추가해주자.

@EnableJpaAuditing 		// JPA Auditing어노테이션들 모두 활성화할 수 있게 함
@SpringBootApplication
public class Application { ... }

 

테스트 코드

기존의 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);
}