[Kotlin] JPA Auditing - Entity 생성, 수정 시간 자동화

by 민갤

Back End /

BaseEntity

@MappedSuperclass
@EntityListeners(AuditingEntityListener::class)
abstract class BaseEntity{
    @CreatedDate
    @Column(nullable = false, updatable = false)
    protected var createDtm: LocalDateTime = LocalDateTime.MIN

    @LastModifiedDate
    @Column(nullable = false)
    protected var modifyDtm: LocalDateTime = LocalDateTime.MIN
}
  • @MappedSuperclass
  • 공통 매핑 정보가 필요할 때 사용. 상속받는 클래스에서 createDtm, modifyDtm도 컬럼으로 인식
  • 해당 Annotation이 선언된 클래스는 Entity가 아니며, 직접 사용될 일이 없기 때문에 추상 클래스로 생성
  • @EntityListeners(AuditingEntityListener::class)
  • Entity에서 이벤트가 발생할 때마다 특정 기능을 수행
  • 여기서 특정 기능은 Auditing
  • @CreatedDate
  • 생성 시간 자동 저장
  • @LastModifiedDate
  • 수정 시간 자동 저장

Domain

@Entity
class User(
	@Column(length = 30, nullable = false)
	private val name: String,

	@Id
	@GeneratedValue(strategy = GenerationType.IDENTITY)
	val id: Long
): BaseEntity() {
}

Application

@EnableJpaAuditing
@SpringBootApplication
class UserApplication

fun main(args: Array<String>) {
	runApplication<UserApplication>(*args)
}
  • @EnableJpaAuditing
  • JPA Auditing 기능을 활성화
  • Main Method가 있는 Class에 적용

Author

민갤

민갤

Back-End Developer

꾸잉꾸잉하고 웁니다.

로그인

디코에 오신 것을 환영해요!
전문가들의 수많은 아티클 창고 🤓