포스트

[TIL] Spring Basics - Applying JPA Auditing

This is a TIL that summarizes how to automatically manage the creation and modification dates of entities using JPA Auditing.

한국어 원문은 여기에서 볼 수 있습니다.
[TIL] Spring Basics - Applying JPA Auditing

What to do today

What I studied

Apply JPA Auditing

Timestamped

  • Spring Data JPA provides JPA Auditing, a function that automatically enters time values.
    • Data creation (created_at) and modification (modified_at) times are very frequently used for various data.
    • It is inefficient to write the creation and modification time of each entity every time.
      1
      2
      3
      4
      5
      6
      7
      8
      9
      10
      11
      12
      13
      14
      15
      
      @Getter
      @MappedSuperclass
      @EntityListeners(AuditingEntityListener.class)
      public abstract class Timestamped {
      
      @CreatedDate
      @Column(updatable = false)
      @Temporal(TemporalType.TIMESTAMP)
      private LocalDateTime createdAt;
      
      @LastModifiedDate
      @Column
      @Temporal(TemporalType.TIMESTAMP)
      private LocalDateTime modifiedAt;
      }
      
  • @MappedSuperclass: When JPA Entity classes inherit the abstract class, member variables declared in the abstract class, such as createdAt and modifiedAt, can be recognized as columns.
  • @EntityListeners(AuditingEntityListner.class): Includes Auditing function in the class.
  • @CreateDate: The time is automatically saved when an Entity object is created and saved.
    • The update = false option was added because the initial creation time is stored and cannot be modified after that.
  • @LastModifiedDate: When changing the value of the searched Entity object, the changed time is automatically saved.
    • Whenever a change occurs after the initial creation time is saved, it is updated to the corresponding change time.
  • @Temporal: Used when mapping date types (java.util.Date, java.util.Calender)
    • There are three separate types in DB: Date, Time, and Timestamp.

Add @EnableJpaAuditing to the class with @SpringBootApplication!

  • @EnableJpaAuditing must be added to convey information that the JPA Auditing function will be used.

Problems & Errors

What to do tomorrow