Kotlin에서 제공하는 class
- 기본으로 equals() / hashCode(), toString, copy() 같은 메서드들을 제공한다.
- copy() 메서드는 얕은 복사만 지원하기 때문에 data class는 불변 클래스로 사용하는 것이 권장된다.
- 순수하게 데이터만 관리하는 클래스로 open 키워드를 통한 상속을 지원하지 않는다.
JPA에서는 data class를 쓰는 것은 추천하지 않는다.
관련 자세한 내용을 다룬 : 블로그
기존 Spring에서 사용하던 JPA 방식과 Kotlin에서 사용하는 방식이 다르기 때문에 Hibernate(JPA)의 요구사항에 대해 정확하게 알 필요가 있다.
정확한 내용은 Hibernate 문서를 참고하시기 바랍니다.
2.5. Entity types
2.5.1. POJO Models
2.5.2. Prefer non-final classes
2.5.3. Implement a no-argumeent constructor
2.5.4. Declare getters and setter for persistent attributes
2.5.5. Providing identifier attribute(s)
2.5.6. Mapping the entity
2.5.7. Implementing equals() and hashCode()
2.5.8. Mapping the entity to a SQL query
2.5.9. Define a custom entity proxy
2.5.10. Dynamic entity proxies using the @Tuplizer annotation
2.5.11. Define a custom entity persister
2.5.12. Access strategies
Gradle or Maven 에서 추가 플러그인 지정으로 @Entity, @Embeddable, @MappedSuperclass 어노테이션이 붙은 모든 클래스에 자동으로 매개변수가 없는 생성자를 만들 수 있다.
// Gradle(Groovy)
plugins {
id 'org.jetbrains.kotlin.plugin.jpa' version '{Kotlin버전}'
}
// Gradle(Kotlin)
plugins {
kotlin("plugin.jpa") version "{Kotlin버전}"
}
코틀린의 모든 클래스는 기본적으로 final 클래스이다.
엔티티 클래스가 final 클래스여도 JPA 사용에는 문제 없지만, 지연 로딩을 사용할 수 없다는 단점이 있다.
// kotlin-spring 플러그인이 있을 경우 all-open 플러그인을 포함하고 있다.
plugins {
id 'org.jetbrains.kotlin.plugin.spring' version '1.7.22'
}
ㅡㅡㅡ
// Gradle (Spring Boot 3.0.0 이상)
plugins {
...
id 'org.jetbrains.kotlin.plugin.allopen' version '{Kotlin버전}' // Gradle(Groovy)
kotlin("plugin.allopen") version "{Kotlin버전}" // Gradle(Kotlin)
...
}
allOpen {
annotation("jakarta.persistence.Entity")
annotation("jakarta.persistence.Embeddable")
annotation("jakarta.persistence.MappedSuperclass")
}
ㅡㅡㅡ
// Gradle (Spring Boot 3.0.0 미만)
plugins {
...
id 'org.jetbrains.kotlin.plugin.allopen' version '{Kotlin버전}' // Gradle(Groovy)
kotlin("plugin.allopen") version "{Kotlin버전}" // Gradle(Kotlin)
...
}
allOpen {
annotation("javax.persistence.Entity")
annotation("javax.persistence.Embeddable")
annotation("javax.persistence.MappedSuperclass")
}
코틀린의 data class
기본적으로 Lombok의 toString(), equals(), hashCode(), copy()를 포함하고 구조 분해를 사용할 수 있는 클래스
[Kotlin/JPA] 코틀린과 JPA를 함께 사용할 때 추가적으로 설정해야 하는 것들과 Data class