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

BaseEntity

Kotlin

1

2

3

4

5

6

7

8

9

10

11

@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

Kotlin

1

2

3

4

5

6

7

8

9

10

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

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

Application

Kotlin

1

2

3

4

5

6

7

@EnableJpaAuditing
@SpringBootApplication
class UserApplication

fun main(args: Array<String>) {
	runApplication<UserApplication>(*args)
}
  • @EnableJpaAuditing

  • JPA Auditing 기능을 활성화

  • Main Method가 있는 Class에 적용

민갤

Back-End Developer

백엔드 개발자입니다.

[Spring Boot] ERROR: IllegalArgumentException

Spring Boot

[Spring Boot] WebMvcConfigurer로 설정 자동화 추가하기

Spring Boot

v5.0