Day 5

Day5

JPA Auditing์œผ๋กœ ์ƒ์„ฑ์‹œ๊ฐ„/์ˆ˜์ •์‹œ๊ฐ„ ์ž๋™ํ™”ํ•˜๊ธฐ

๋ณดํ†ต Entity์—๋Š” ํ•ด๋‹น ๋ฐ์ดํ„ฐ์˜ ์ƒ์„ฑ์‹œ๊ฐ„๊ณผ ์ˆ˜์ •์‹œ๊ฐ„์„ ํฌํ•จํ•˜๊ฒŒ ๋จ โ‡’ ์œ ์ง€๋ณด์ˆ˜์‹œ ์ค‘์š”ํ•œ ์ •๋ณด์ด๊ธฐ ๋•Œ๋ฌธ์— ํ•„์š”ํ•˜์ง€๋งŒ ์ผ์ผ์ด ์ฝ”๋“œ๋ฅผ ์ถ”๊ฐ€ํ•˜๊ธฐ์—๋Š” ๊ท€์ฐฎ๊ณ  ์ฝ”๋“œ๊ฐ€ ๊ธธ์–ด์ง€๊ธฐ ๋•Œ๋ฌธ์— JPA Auditing์„ ์‚ฌ์šฉํ•จ

๐Ÿ‘‰LocalDate๋ฅผ ์‚ฌ์šฉ

java8๋ถ€ํ„ฐ ๊ธฐ๋ณธ ๋‚ ์งœ ํƒ€์ž…์ธ Date์˜ ๋ฌธ์ œ์ ์„ ๋ณด์•ˆํ•œ ํƒ€์ž…

Entity๋“ค์˜ createdDate, modifiedDate๋ฅผ ์ž๋™์œผ๋กœ ๊ด€๋ฆฌํ•˜๋Š” ์—ญํ• 

src/main/java/com/kyu/book/springboot/domain/BaseTimeEntity.class

package com.kyu.book.springboot.domain;

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
@MappedSuperclass
@EntityListeners(AuditingEntityListener.class)
public class BaseTimeEntity {
    @CreatedDate
    private LocalDateTime createdDate;
    
    @LastModifiedDate
    private LocalDateTime modifiedDate;
}

@MappedSuperclass

  • JPA Entity ํด๋ž˜์Šค๋“ค์ด BaseTimeEntity์„ ์ƒ์†ํ•  ๊ฒฝ์šฐ ํ•„๋“œ๋“ค(createdDate, modifiedDate)๋„ ์นผ๋Ÿผ์œผ๋กœ ์ธ์‹ํ•˜๋„๋ก ํ•ฉ๋‹ˆ๋‹ค

@EntityListeners(AuditingEntityListener.class)

  • BaseTimeEntity ํด๋ž˜์Šค์— Auditing ๊ธฐ๋Šฅ์„ ํฌํ•จ์‹œํ‚ด

@CreatedDate

  • Entity๊ฐ€ ์ƒ์„ฑ๋˜์–ด ์ €์žฅ๋  ๋•Œ ์‹œ๊ฐ„์ด ์ž๋™ ์ €์žฅ๋ฉ๋‹ˆ๋‹ค.

@LastModifiedDate

  • ์กฐํšŒํ•œ Entity์˜ ๊ฐ’์„ ๋ณ€๊ฒฝํ•  ๋•Œ ์‹œ๊ฐ„์ด ์ž๋™ ์ €์žฅ๋จ

๊ทธ๋ฆฌ๊ณ  Posts ํด๋ž˜์Šค๊ฐ€ BaseTimeEntity๋ฅผ ์ƒ์†๋ฐ›๋„๋ก ์„ค์ •

๋งˆ์ง€๋ง‰์œผ๋กœ JPA Auditing์„ ํ™œ์„ฑํ™”ํ•˜๊ธฐ ์œ„ํ•ด์„œ

/src/main/java/com/kyu/book/springboot/application.class

@EnableJpaAuditing
@SpringBootApplication
public class Application {
    public static void main(String[] args) {
        SpringApplication.run(Application.class, args);
    }
}

์ž‘๋™ํ•˜๋Š”์ง€ ํ™•์ธํ•˜๊ธฐ ์œ„ํ•ด์„œ test์ฝ”๋“œ์ž‘์„ฑ

src/test/java/com/kyu/book/springboot/domain/posts/PostRepository.class

@Test
public void BaseTimeEntity_enroll(){
    LocalDateTime now = LocalDateTime.of(2021,1,5,0,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(">>>>>>> createDate="+posts.getCreatedDate()+", modifiedDate="+posts.getModifiedDate());

    assertThat(posts.getCreatedDate()).isAfter(now);
    assertThat(posts.getModifiedDate()).isAfter(now);
}

Last updated

Was this helpful?