Spring boot升级,使Hibernate出现ClassCastException

gojuced7  于 8个月前  发布在  Spring
关注(0)|答案(1)|浏览(90)

作为上下文,应用程序使用spring-boot 2.5.0。从2.5.0到2.5.15的升级进行得很顺利。但是从2.5.15 -> 2.6.0开始,在运行时,在父类和子类之间的转换期间抛出Hibernate ClassCastException。这个spring boot升级,也是Hibernate从5.4.31.Final升级到5.6.15.Final的副作用。基于Hibernate迁移指南,我没有看到任何我必须改变的东西。
为了简单起见,Hibernate表看起来像这样:

@Entity
@Inheritance(strategy = InheritanceType.SINGLE_TABLE)
@DiscriminatorColumn(name = "classType", discriminatorType = DiscriminatorType.STRING)
public abstract class Parent {
...
}

@Entity
@DiscriminatorValue("child1")
public class Child1 extends Parent {
...
}

@Entity
@DiscriminatorValue("child2")
public class Child2 extends Parent {
...
}

错误出现在执行以下代码的服务中的某个位置:

Child1 child1 = (Child1) repo.getById(id);

基本上直到升级repo.getById(id);返回已成功转换为Child 1的Parent实体。repo.getById(id);返回一个不能转换为Child 1的代理。
这是错误:
java.lang.ClassCastException:无法将类Parent$HibernateProxy$hJgxv3zc强制转换为类Child 1(Parent$HibernateProxy$hJgxv3zc和Child 1位于加载程序“app”的未命名模块中)
我看到Hibernate.unproxy(repo.getById(id))返回了真实的实体,但为什么在它工作之前?以及我可以在spring-data或Hibernate中进行哪些配置,以像uprade之前一样工作?

2ic8powd

2ic8powd1#

即使在Hibernate的5.4.x版本之前,它也工作得很好,但在5.6.x版本中,它不再工作了。因此,解决方法是:
1.使用Hibernate.unproxy(repo.getById(id))。这将直接检索可以正确转换的实体
1.使用repo.findById(id)。同样,这将检索实体。

相关问题