kotlin

Kotlin - Spring JPA entity 매개변수 없는 생성자 플러그인

codeManager 2024. 3. 19. 22:05
반응형

 

Kotlin으로 Spring JPA를 사용하면 Entity 클래스를 만들 때 이슈에 대해서 알아보겠습니다.


Hibernate Entity 가이드를 보면 Entity의 조건이 나와 있습니다.

 

https://docs.jboss.org/hibernate/orm/current/userguide/html_single/Hibernate_User_Guide.html#entity

 

Hibernate ORM User Guide

Starting in 6.0, Hibernate allows to configure the default semantics of List without @OrderColumn via the hibernate.mapping.default_list_semantics setting. To switch to the more natural LIST semantics with an implicit order-column, set the setting to LIST.

docs.jboss.org

 

The entity class must have a public or protected no-argument constructor. It may define additional constructors as well.

 

entity 클래스는 매개변수가 없는 생성자를 가져야 한다고 가이드에 나와 있습니다.

 

 

Kotlin JPA에서 @Entity 어노테이션으로 entity를 생성하면 보통 다음과 같습니다.

 

@Entity
@Table(name = "person")
data class Person(
    @Id
    @Column(name = "id")
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    val id: Long,

    @Column(name = "age")
    val age: Long,

    @Column(name = "name")
    val age: String
)

 

이렇게 Entity를 생성하면 에러가 발생합니다.

 

Class 'Person' should have [public, protected] no-arg constructor

 

매개변수가 없는 생성자를 선언해주지 않아서 발생하는 에러입니다.

 

이럴 경우 Entity마다 생성자를 작성하는 것보다 플러그인을 설정해주면 간편합니다.

 

//build.gradle.kts
plugins {
	kotlin("plugin.jpa") version "1.6.9"
}

 

build.gradle.kts 파일에 plugin.jpa를 설정해주면 해결됩니다.

반응형