[JPA] 중복 시간 자동 채우기(BaseTimeEntity)

Lui.Slki·2026년 1월 10일

Quick Tips

목록 보기
2/5

Spring Data JPA Auditing으로 createdAt / updatedAt 자동 채우기

엔티티마다 생성일/수정일 컬럼을 매번 넣기 귀찮을 때, 공통 베이스 클래스를 만들어두면 편하다.

@MappedSuperclass + @CreatedDate / @LastModifiedDate를 쓰면 저장/수정 시점에 시간이 자동으로 채워진다.

- 예시

@Getter
@MappedSuperclass
@EntityListeners(AuditingEntityListener.class) // Auditing 동작 스위치
public abstract class BaseTimeEntity {

    @CreatedDate
    @Column(name = "create_dt", nullable = false, updatable = false)
    private LocalDateTime createDt;

    @LastModifiedDate
    @Column(name = "update_dt")
    private LocalDateTime updateDt;
}

- 사용방법

엔티티에서 상속만 하면, 해당 엔티티 테이블에 create_dt, update_dt 컬럼이 포함된다.

@Entity
public class Lesson extends BaseTimeEntity {
    @Id @GeneratedValue
    private Long lessonId;

    // ...
}

- 반드시 필요한 설정 : Auditing 활성화

Spring Boot에서 Auditing이 자동으로 돌려면 설정 클래스(또는 메인 클래스)에 아래를 추가해야 한다.

  • 메인 클래스
@EnableJpaAuditing
@SpringBootApplication
public class MuzinApplication { }

혹은,

  • 설정 클래스(config 파일 생성) 분리
@Configuration
@EnableJpaAuditing
public class JpaConfig { }

주의할 점

  • @MappedSuperclass는 테이블로 생성되지 않음 (상속받은 엔티티 테이블에 컬럼이 생김)
  • @CreatedDate, @LastModifiedDate는 JPA Auditing 활성화(@EnableJpaAuditing)가 없으면 안 채워짐
  • createDt는 updatable=false로 두는 게 일반적으로 안전 (생성일은 수정되면 안 되니까)

0개의 댓글