如果未使用“Hibernate.unproxy”初始化Hibernate实体属性,则该属性为“null”`
我有一个类型为如果未使用“Hibernate.unproxy”初始化Hibernate实体属性,则该属性为“null”`,hibernate,spring-boot,kotlin,Hibernate,Spring Boot,Kotlin,我有一个类型为typeproperty的实体对象是null(它在数据库中不是null)。当我在实体对象上调用Hibernate.unproxy,并查看uproxied对象typepropery时,它不是空的。这个实体是从其他实体继承的(我之所以提到它,是因为我没有看到非继承实体的这种行为) 以下是kotlin代码: open class HealthValue { @get:Id open var id: UUID? = null @get:ManyToOne(f
type
property的实体对象是null
(它在数据库中不是null)。当我在实体对象上调用Hibernate.unproxy
,并查看uproxied对象type
propery时,它不是空的。这个实体是从其他实体继承的(我之所以提到它,是因为我没有看到非继承实体的这种行为)
以下是kotlin代码:
open class HealthValue {
@get:Id
open var id: UUID? = null
@get:ManyToOne(fetch = FetchType.LAZY)
open var healthValueType: HealthValueType? = null
}
class ObservedHealthValue : HealthValue() {
}
open class HealthValueType {
@get:Id
open var id: UUID? = null
@get:Enumerated(EnumType.STRING)
@get:Column(nullable = false)
var type: ObservationType? = null
}
class SelectionValueType : HealthValueType() {
}
下面是bug演示的片段:
@Transactional
fun method(id: UUID) {
val healthValue= entityManager.find(ObservedHealthValue::class.java, id)
val type1 = healthValue.healthValueType!!.type // this value is null
val type2 = Hibernate.unproxy(healthValue.healthValueType!!).type // this is not null
}
这种行为看起来很奇怪,不确定使用Hibernate.unproxy
是否正确。你知道为什么会这样吗?如何解决
我的hibernate版本是:5.3.7.Final(它来自gradle dependecy
compile(“org.springframework.boot:spring boot starter data jpa”)
启用了'org.springframework.boot'version'2.2.0.RELEASE'
插件)我找到了原因——这是因为type
字段没有打开。在kotlin中,默认情况下所有字段都是final
,因此您需要将它们指定为open
。所以它是这样工作的:
open class HealthValueType {
@get:Id
open var id: UUID? = null
@get:Enumerated(EnumType.STRING)
@get:Column(nullable = false)
open var type: ObservationType? = null
}
但是,更好的解决方案是使用插件