Java/Spring

[Spirng] 엔티티 생성, 수정시간 추가

뉴벡엔드 2024. 5. 16. 12:36

 

@CreateData : 엔티티가 생성될 때 생성시간을 컬럼에 저장합니다.

@LastModifiedDate : 엔티티가 수정될 때 마지막으로 수정된 시간을 컬럼에 저장합니다.

@EntityListeners(AuditingEntityListener.class) : 엔티티의 생성 및 수정 시간을 자동으로 감시하고 기록 합니다.

@EnableJpaAuditing : 자동으로 업데이트합니다,

import jakarta.persistence.*;
import lombok.Getter;
import lombok.NoArgsConstructor;
import org.springframework.data.annotation.CreatedDate;
import org.springframework.data.annotation.LastModifiedDate;
import org.springframework.data.jpa.domain.support.AuditingEntityListener;

import java.time.LocalDateTime;

@EntityListeners(AuditingEntityListener.class) //엔티티의 생성 및 수정시간을 자동으로 감시하고 기록
@Entity
@Getter
@NoArgsConstructor
public class Article {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name = "id", updatable = false)
    private Long id;

    @CreatedDate //엔티티가 생성될 때 생성 시간 지정
    @Column(name = "created_at")
    private LocalDateTime createdAt;

    @LastModifiedDate //엔티티가 수정될 때 수정 시간 저장
    @Column(name = "update_at")
    private LocalDateTime updateAt;

}

 

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.data.jpa.repository.config.EnableJpaAuditing;

@EnableJpaAuditing //created_at, updated_at 자동업데이트
@SpringBootApplication
public class SpringBootDeveloperApplication {
    public static void main(String[] args) {
        // Correct class reference for SpringApplication.run
        SpringApplication.run(SpringBootDeveloperApplication.class, args);
    }
}
반응형