You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

升级至Micronaut 4时遇类型不兼容错误:HibernateProxy与ErrorRowError

解决Micronaut 4升级中HibernateProxy与实体类类型不兼容问题

升级Micronaut到4版本并完成javax到jakarta迁移后,实体类ErrorRowError的equals方法中出现Incompatible types: HibernateProxy and ErrorRowError错误,核心原因是Hibernate 6(Micronaut 4默认依赖版本)重构了代理机制,实体类不再直接实现HibernateProxy接口,原来的this is HibernateProxy判断逻辑不再成立。

解决方案

使用Hibernate官方提供的Hibernate.getClass()工具方法替代手动判断代理对象,该方法能自动识别实体对象或代理对象,返回其真实的持久化类,代码更简洁且兼容性更强。

修改后的代码

首先引入Hibernate工具类:

import org.hibernate.Hibernate

然后替换原equals方法:

override fun equals(other: Any?): Boolean {
    if (this === other) return true
    if (other == null) return false
    val thisEffectiveClass = Hibernate.getClass(this)
    val oEffectiveClass = Hibernate.getClass(other)
    if (thisEffectiveClass != oEffectiveClass) return false
    other as ErrorRowError

    return id != null && id == other.id
}

补充说明

  • 原代码中判断this is HibernateProxy完全多余:在Hibernate 6中,实体类本身永远不会是HibernateProxy的实例,只有懒加载产生的动态代理对象才会实现该接口,所以这个判断会触发类型不兼容错误。
  • Hibernate.getClass()是Hibernate推荐的获取实体真实类型的标准方式,同时兼容Hibernate 5和6版本,避免手动处理代理逻辑的冗余和错误。

内容的提问来源于stack exchange,提问作者Bart Romano

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.09 16:33:29