[Spring] Jpa . Auditing 특정날짜시간형식지정하기

hyewon jeong·2023년 6월 25일
1

Spring

목록 보기
47/59
@Getter             
@MappedSuperclass   //멤버 변수가 컬럼이 되도록합니다.
@EntityListeners(AuditingEntityListener.class)//변경 되었을때 자동으로 기록합니다.
public class Timestamped implements Serializable {

    @JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "yyyy-MM-dd'작성시간'HH:mm:ss")
    @JsonSerialize(using = LocalDateTimeSerializer.class)
    @JsonDeserialize(using = LocalDateTimeDeserializer.class)
    @CreatedDate//최소 생성시점
    private LocalDateTime createdDate;
    private String createdDateString;

    @JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "yyyy-MM-dd'작성시간'HH:mm:ss")
    @JsonSerialize(using = LocalDateTimeSerializer.class)
    @JsonDeserialize(using = LocalDateTimeDeserializer.class)
    @LastModifiedDate//마지막 변경시점
    private LocalDateTime modifiedDate;


    @PrePersist
    public void onPrePersist(){
        this.createdDateString = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy.MM.dd"));
    }
}
  • @MappedSuperclass: 이 클래스는 엔티티 클래스의 공통 기능을 제공하는 추상 클래스임을 나타냅니다. JPA에서 사용되며, 해당 클래스의 멤버 변수가 데이터베이스의 컬럼으로 매핑되도록 합니다.
  • @EntityListeners(AuditingEntityListener.class): 이 클래스의 엔티티 객체가 변경될 때 자동으로 변경 이력을 기록하기 위한 설정입니다.
  • AuditingEntityListener는 변경 이력을 처리하는 리스너 클래스를 지정합니다.
  • @CreatedDate: 엔티티 객체가 생성된 일자와 시간을 저장하는 필드를 나타냅니다. 이 어노테이션은 생성 시점에 해당 필드에 현재 일자와 시간 정보를 자동으로 설정합니다.

1. 직렬화 클래스 상속하여 특정시간형식을 지정한다.

1. gradle에 아래와 같이 추가하고

//자바 역직렬화 문제 해결 패키지
implementation 'com.fasterxml.jackson.datatype:jackson-datatype-jsr310'
implementation 'com.fasterxml.jackson.core:jackson-databind'

2-1. 직렬화 및 역직렬화 에 필요한 어노테이션

  • @JsonFormat: JSON 직렬화 및 역직렬화 시 날짜 및 시간 필드의 형식을 지정합니다. 이 예시에서는 "yyyy-MM-dd'작성시간'HH:mm:ss" 형식으로 직렬화 및 역직렬화됩니다.
  • @JsonSerialize: 필드를 JSON으로 직렬화할 때 사용할 커스텀 직렬화 클래스를 지정합니다. 이 예시에서는 LocalDateTimeSerializer 클래스를 사용하여 LocalDateTime 필드를 직렬화합니다.
  • @JsonDeserialize: JSON에서 필드를 역직렬화할 때 사용할 커스텀 역직렬화 클래스를 지정합니다. 이 예시에서는 LocalDateTimeDeserializer 클래스를 사용하여 LocalDateTime 필드를 역직렬화합니다.

2-2. 케이스별 적용 결과

    private String createdDateString;

.....
    @PrePersist // 영속성컨텍스트가 일어나기전에  시행함 
    public void onPrePersist(){
        this.createdDateString = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy.MM.dd"));
    }
  • private String createdDateString;: 생성된 일자와 시간을 특정 형식의 문자열로 저장하는 변수입니다. @PrePersist 메서드에서 현재 일자와 시간을 이용하여 값을 설정합니다.

createdDateString 필드로 날짜를 받을때

    this.createdDate = faq.getCreatedDateString();

CreatedDate 필드로 날짜를 받을때

  private final LocalDateTime createdDate;
  

  • @JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "yyyy-MM-dd'작성시간'HH:mm:ss")

    "작성시간" 부분이 포맷 문자열 안에서 문자열 리터럴로 사용되고 있습니다. 따라서 실제로는 "작성시간"이라는 문자열이 포함되어 있는 형태로 직렬화됩니다.

따라서 결과로 출력되는 "createdDate" : "2023-06-25T20:12:17.392801"는 "yyyy-MM-dd'작성시간'HH:mm:ss" 패턴에 따라 포맷팅된 문자열입니다.

CreatedDate 필드로 날짜를 받을때 + 개별 포맷형식 지정

 @JsonFormat(shape= JsonFormat.Shape.STRING, pattern="yyyy-MM-dd HH:mm")
  private final LocalDateTime createdDate;
  
      this.createdDate = faq.getCreatedDate();

또는 TimeStamped.class 를 serialize 상속하지 않은채로 해당 필드에 형식 지정해줘도 된다.

@Getter
@MappedSuperclass
@EntityListeners(AuditingEntityListener.class)
public class TimeStamped {

  @JsonSerialize(using = LocalDateTimeSerializer.class)
  @JsonDeserialize(using = LocalDateTimeDeserializer.class)
  @JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "yyyy-MM-dd HH:mm")
    @CreatedDate
  private LocalDateTime createdDate;


  @JsonSerialize(using = LocalDateTimeSerializer.class)
  @JsonDeserialize(using = LocalDateTimeDeserializer.class)
  @JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "yyyy-MM-dd HH:mm")
  @LastModifiedDate
  private LocalDateTime modifiedDate;

}

캐싱 사용하는 객체에 auditing 상속 받아 사용할때 주의 할점

https://velog.io/@wonizizi99/%EC%97%90%EB%9F%AC%EB%85%B8%ED%8A%B8-Java-8-datetime-type-java.time.LocalDateTime-not-supported-by-default

[Spring]Data JPA, Auditing적용 및 Auditing 직접 구현하기

profile
개발자꿈나무

4개의 댓글

comment-user-thumbnail
2023년 6월 26일

므집니다!!!

1개의 답글
comment-user-thumbnail
2023년 7월 2일

https://melonplaymods.com/2023/06/11/fnaf-mod-for-melon-playground/
https://melonplaymods.com/2023/06/11/howitzer-mod-for-melon-playground/
https://melonplaymods.com/2023/06/11/zeta-ultraman-mod-for-melon-playground/
https://melonplaymods.com/2023/06/10/rare-wubbox-mod-for-melon-playground/
https://melonplaymods.com/2023/06/11/train-mod-for-melon-playground-4/
https://melonplaymods.com/2023/06/10/dash-attack-titan-mod-for-melon-playground/
https://melonplaymods.com/2023/06/10/bendy-mod-for-melon-playground/
https://melonplaymods.com/2023/06/11/pack-of-robots-21-characters-mod-for-melon-playground/
https://melonplaymods.com/2023/06/10/ben-10-mod-for-melon-playground/
https://melonplaymods.com/2023/06/10/ninja-mod-for-melon-playground-2/
https://melonplaymods.com/2023/06/11/kv-2-mod-for-melon-playground/
https://melonplaymods.com/2023/06/10/doors-library-mod-for-melon-playground/
https://melonplaymods.com/2023/06/10/banana-mod-for-melon-playground/
https://melonplaymods.com/2023/06/11/helicopter-mi-26-mod-for-melon-playground/
https://melonplaymods.com/2023/06/10/ch53k-transport-helicopter-mod-for-melon-playground/
https://melonplaymods.com/2023/06/10/pack-for-vegetables-and-fruits-mod-for-melon-playground/
https://melonplaymods.com/2023/06/10/ww2-weapon-mod-for-melon-playground/
https://melonplaymods.com/2023/06/10/people-sandbox35-mod-for-melon-playground/
https://melonplaymods.com/2023/06/11/mechanical-spider-mod-for-melon-playground/
https://melonplaymods.com/2023/06/11/roblox-doors-theme-pack-mod-for-melon-playground/

답글 달기
comment-user-thumbnail
2023년 7월 2일

https://melonplaymods.com/2023/06/10/submarine-dmitry-donskoy-mod-for-melon-playground/
https://melonplaymods.com/2023/06/11/room-furniture-mod-for-melon-playground/
https://melonplaymods.com/2023/06/11/russian-german-and-ukrainian-flags-mod-for-melon-playground/
https://melonplaymods.com/2023/06/10/e-girl-mod-for-melon-playground/
https://melonplaymods.com/2023/06/11/piggynpc-mod-for-melon-playground/
https://melonplaymods.com/2023/06/10/eddsworld-mod-for-melon-playground/
https://melonplaymods.com/2023/06/11/ersimov-mod-for-melon-playground/
https://melonplaymods.com/2023/06/10/megatron-mod-for-melon-playground/
https://melonplaymods.com/2023/06/11/pak-organs-mod-for-melon-playground/
https://melonplaymods.com/2023/06/11/raiden-from-metal-gear-solid-2npc-mod-for-melon-playground/
https://melonplaymods.com/2023/06/10/katakuri-with-trident-mochi-skill-mod-for-melon-playground/
https://melonplaymods.com/2023/06/11/naruto-akatsuki-mod-for-melon-playground/
https://melonplaymods.com/2023/06/11/bendy-ax-bendys-ax-mod-for-melon-playground/
https://melonplaymods.com/2023/06/11/all-terrain-vehicle-caucasian-2-mod-for-melon-playground/
https://melonplaymods.com/2023/06/10/functional-chainsawman-mod-for-melon-playground/
https://melonplaymods.com/2023/06/11/german-soldiers-from-wwiisvproplayer-mod-for-melon-playground/
https://melonplaymods.com/2023/06/11/godzilla-mod-for-melon-playground-3/
https://melonplaymods.com/2023/06/11/terraria-melee-pack-v0-3-melee-weapons-mod-for-melon-playground/
https://melonplaymods.com/2023/06/11/piggy-book-1-piggy-book-1-characters-mod-for-melon-playground/
https://melonplaymods.com/2023/06/11/desk-lamp-mod-for-melon-playground-2/

답글 달기