根据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?