根据 JPA 的要求,@Entity
类应该有一个默认(非 arg)构造函数,以便在从数据库中检索对象时实例化它们。
在 Kotlin 中,在主构造函数中声明属性非常方便,如下例所示:
class Person(val name: String, val age: Int) { /* ... */ }
但是当非参数构造函数被声明为辅助构造函数时,它需要传递主构造函数的值,因此它们需要一些有效值,如下所示:
@Entity
class Person(val name: String, val age: Int) {
private constructor(): this("", 0)
}
如果属性有一些比 String
和 Int
更复杂的类型并且它们不可为空,那么为它们提供值看起来很糟糕,尤其是当主构造函数和 init
block 中有很多代码时,并且当参数被积极使用时——当它们要通过反射重新分配时,大部分代码将被再次执行。
另外,val
-properties 不能在构造函数执行后重新赋值,所以也就失去了不变性。
所以问题是:如何在不重复代码、选择“神奇”初始值和丧失不变性的情况下使 Kotlin 代码适应 JPA?
附:除了 JPA 之外,Hibernate 真的可以构造没有默认构造函数的对象吗?
最佳答案
从 Kotlin 1.0.6 开始,kotlin-noarg
编译器插件会为已使用选定注解进行注解的类生成合成默认构造函数。
如果你使用 gradle,应用 kotlin-jpa
插件就足以为带有 @Entity
注释的类生成默认构造函数:
buildscript {
dependencies {
classpath "org.jetbrains.kotlin:kotlin-noarg:$kotlin_version"
}
}
apply plugin: "kotlin-jpa"
对于 Maven:
<plugin>
<artifactId>kotlin-maven-plugin</artifactId>
<groupId>org.jetbrains.kotlin</groupId>
<version>${kotlin.version}</version>
<configuration>
<compilerPlugins>
<plugin>jpa</plugin>
</compilerPlugins>
</configuration>
<dependencies>
<dependency>
<groupId>org.jetbrains.kotlin</groupId>
<artifactId>kotlin-maven-noarg</artifactId>
<version>${kotlin.version}</version>
</dependency>
</dependencies>
</plugin>
关于hibernate - 带有 JPA : default constructor hell 的 Kotlin,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32038177/