spring-data-jpa java.lang.ClassCastException:无法将类com.sun.proxy.$Proxy379强制转换为类org. hib. query.internal.NativeQueryImpl

iyfjxgzm  于 2022-11-10  发布在  Spring
关注(0)|答案(1)|浏览(2005)

java.lang.ClassCastException:无法将类com.sun.proxy.$Proxy379强制转换为类org. hib. query.internal.NativeQueryImpl(com.sun.proxy.$Proxy379和org. hib. query.internal.NativeQueryImpl位于加载程序“应用程序”的未命名模块中)
当我试图在springdatajpa自定义存储库中转换它时,我遇到了这个异常。

Query q = entityManager.createNativeQuery(sqlBuffer.toString());
    // BELOW LINES WILL GIVE US THE MAP OF PROPERTIES
    org.hibernate.query.internal.NativeQueryImpl hibernateQuery = ((org.hibernate.query.internal.NativeQueryImpl) q);
    hibernateQuery.setResultTransformer(AliasToEntityOrderedMapResultTransformer.INSTANCE);

    return q.getResultList();

我在以下位置收到异常:查询结果返回给用户,用户可以在查询结果返回之前返回查询结果。

sg24os4d

sg24os4d1#

entityManager.createNativeQuery不需要直接传回Query界面的基础提供者实作(例如NativeQueryImpl)。
EntityManager#getDelegate返回Hibernate的session,然后可以使用它从SQL字符串返回create the native query。这将IMHO接近于得到NativeQueryImpl类。但我也不会依赖于此-Hibernate的Session预计将返回NativeQuery示例。这可能是今天的org.hibernate.query.internal.NativeQueryImpl,而明天将是非常不同的。
我个人更喜欢使用NamedNativeQuery。作为一般原则,总是只使用声明的接口,永远不要转换为Impl类。

相关问题