[JPA] - createdAt, updatedAt 자동 입력

Ogu·2022년 12월 7일
0

SpringBoot

목록 보기
2/17

@CreatedDate & @LastModifiedDate

선행 설정 1) @EntityListeners

위 두개의 어노테이션을 사용하기 위해서는 @EntityListeners(AuditingEntityListener.class) 어노테이션이 필요하다.
엔티티를 DB에 적용하기 이전에 콜백을 요청할 수 있는 어노테이션이다.

선행 설정 2) @EnableJpaAuditing

SpringApplication에 @EnableJpaAuditing 붙이기
보통 Springboot 를 실행시키는 클래스 상단에 많이 사용한다.
JPA Auditing(감시, 감사) 기능을 활성화하기 위한 어노테이션으로 createdDate, modifiedDate처럼 DB에 데이터가 저장되거나 수정될 때 언제, 누가 했는지를 자동으로 관리한다.

계좌 시스템 프로젝트에서는 config패키지 > JpaAuditingConfiguration 클래스에 설정했다.

createdDate

엔티티 생성 시 특정 필드를 자동으로 데이터베이스에 매핑해주기 위해 사용한다.

LastModifiedDate

엔티티 최종 수정 날짜를 자동으로 데이터베이스에 매핑해주기 위해 사용한다.

ex)

@Getter
@Setter
@NoArgsConstructor
@AllArgsConstructor
@Builder
@Entity  // 설정 클래스
@EntityListeners(AuditingEntityListener.class)
public class Account {
    @Id
    @GeneratedValue
    private Long id;   // Account table에 pk로 id를 지정

    @ManyToOne  // (계좌:사용자 = n : 1)
    private AccountUser accountUser;
    private String accountNumber;

    @Enumerated(EnumType.STRING)
    private AccountStatus accountStatus;
    private Long balance;

    private LocalDateTime registeredAt;
    private LocalDateTime unregisteredAt;

    @CreatedDate
    private LocalDateTime createdAt;
    @LastModifiedDate
    private LocalDateTime updatedAt;
}

참고 URL

profile
私はゲームと日本が好きなBackend Developer志望生のOguです🐤🐤

0개의 댓글