大多数Kotlin JPA示例代码都是这样的
class Person(val name: String, val age: Int) { /* ... */ }
Run Code Online (Sandbox Code Playgroud)
甚至
data class Person(val name: String="", val age: Int=0) { /* ... */ }
Run Code Online (Sandbox Code Playgroud)
现在,Hibernate用户指南,以及我认为其他几个ORM,声明他们通常想要创建代理或以其他方式扩展模型类,但是为了允许在Kotlin中必须明确定义类open.数据类目前这是不可能的,从我自己的经验来看,我认为大多数人在Kotlin中编写JPA实体时都没有考虑过.
所以,为了解决我的问题(毕竟这是stackoverflow),这样做是否足够
open class Person(val name: String, val age: Int) { /* ... */ }
Run Code Online (Sandbox Code Playgroud)
或者我们真的要做
open class Person(open val name: String, open val age: Int) { /* ... */ }
Run Code Online (Sandbox Code Playgroud)
不必要地阻碍ORM正常工作?
如果确实有害,我们应该建议向IntelliJ IDEA添加一个警告,如果一个类有一个@Entity注释,它应该被定义open.
假设以下代码:
class ConstructMe<T> {}
data class Test<T> constructor(var supplier: () -> ConstructMe<T>) {}
fun main(args: Array<String>) {
works<Int>()
breaks<Int>()
}
fun <T> works() {
Test<T>({ ConstructMe<T>() }) // (1) any one class type parameter can be removed like:
Test({ ConstructMe<T>() }) // (2) still works (class type inferred by argument type)
Test<T>({ ConstructMe() }) // (3) still works (argument type inferred by class type)
}
fun <T> breaks() {
Test<T>(::ConstructMe) // type interference failed (should probably work like (3); compiler …Run Code Online (Sandbox Code Playgroud) generics reflection type-parameter kotlin constructor-reference