根据JPA的要求,@Entity个类应该有一个默认(非arg)构造函数,以便在从数据库检索对象时实例化它们.

In Kotlin, properties are very convenient to declare within the primary constructor, as in the following example:

class Person(val name: String, val age: Int) { /* ... */ }

但是,当非arg构造函数被声明为次要构造函数时,它需要传递主构造函数的值,因此它们需要一些有效值,如下所示:

@Entity
class Person(val name: String, val age: Int) {
    private constructor(): this("", 0)
}

In case when the properties have some more complex type than just String and Int and they're non-nullable, it looks totally bad to provide the values for them, especially when there's much code in primary constructor and init blocks and when the parameters are actively used -- when they're to be reassigned through reflection most of the code is going to be executed again.

Moreover, val-properties cannot be reassigned after the constructor executes, so immutability is also lost.

So the question is: how can Kotlin code be adapted to work with JPA without code duplication, choosing "magic" initial values and loss of immutability?

P.S. Is it true that Hibernate aside of JPA can construct objects with no default constructor?

推荐答案

As of Kotlin 1.0.6kotlin-noarg编译器插件为已使用选定注释进行注释的类生成合成默认构造函数.

If you use gradle, applying the kotlin-jpa plugin is enough to generate default constructors for classes annotated with @Entity:

buildscript {
    dependencies {
        classpath "org.jetbrains.kotlin:kotlin-noarg:$kotlin_version"
    }
}

apply plugin: "kotlin-jpa"

For 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>

Kotlin相关问答推荐

文本正在被切断在200%的屏幕比例在Jetpack Compose

用浮点数或十进制数给出错误答案的阶乘计算

如何进行基于lambda/谓词的两个列表的交集?

Kotlin中是否可以混合使用推断和显式的通用类型参数?

在 map 中查找键与在 kotlin 中查找 firstOrNull

为什么 trySend 会发出假数据?

使用事务时未调用 Kafka ConsumerInterceptor onCommit

验证构造函数中的值组合

使用 Compose for Desktop Bundle 文件

错误:cannot find symbol import com.gourav.news.databinding.ActivityDetailBindingImpl;

有没有办法重用 Job 实例?

如何从 Java 中隐藏 Kotlin 的 lateinit var 支持字段?

Kotlin - mutableMapOf() 会保留我输入的顺序

什么是开放式property?为什么我不能将其设置器设为private私有?

Kotlin:使用Gradle进行增量编译

Kotlin:子构造函数如何使用其父构造函数的辅助构造函数?

类型不匹配:推断类型为 LoginActivity 但应为 LifecycleOwner

判断EditText是否为空kotlin android

如何在kotlin用mockito模仿lambda

函数引用和lambdas