【问题标题】:Hibernate entity property is `null` if it is not initialized with `Hibernate.unproxy`如果 Hibernate 实体属性未使用“Hibernate.unproxy”进行初始化,则为“null”
【发布时间】:2020-03-03 03:38:16
【问题描述】:

我有type 属性的实体对象是null(它在数据库中不为空)。当我在实体对象上调用Hibernate.unproxy 并查看被代理的对象type 属性时,它不为空。这个实体是从其他实体继承而来的(我之所以提到它是因为我没有看到非继承实体的这种行为)。

这里是实体 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() {

}

这里是带有错误演示的 sn-p:

@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 是正确的方法。你有什么想法为什么会发生,如何解决这个问题?

我的休眠版本是:5.3.7.Final(它来自 gradledependecy compile("org.springframework.boot:spring-boot-starter-data-jpa") 并启用了'org.springframework.boot' version '2.2.0.RELEASE' 插件)

【问题讨论】:

    标签: hibernate spring-boot kotlin


    【解决方案1】:

    我找到了 reson - 这是因为 type 字段不是 open。在 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
    }
    

    但是,更好的解决方案是使用kotlin-allopen 插件。

    【讨论】:

      猜你喜欢
      • 2021-10-12
      • 1970-01-01
      • 1970-01-01
      • 2016-10-05
      • 2021-08-25
      • 2019-03-20
      • 2023-03-13
      • 1970-01-01
      • 2016-08-06
      相关资源
      最近更新 更多