【发布时间】:2017-12-10 14:06:13
【问题描述】:
过去也有类似的问题,但没有真正的解决方案。
我正在将 Hibernate Web 应用程序转换为支持 JPA。到目前为止只有1个DAO类,转换为JPA后已经出现以下错误。
注意:我们没有使用 Spring-Boot,因此之前的答案不适用于我们的案例。
java.lang.ClassCastException: org.springframework.orm.hibernate5.SessionHolder cannot be cast to org.springframework.orm.jpa.EntityManagerHolder
at org.springframework.orm.jpa.EntityManagerFactoryUtils.doGetTransactionalEntityManager(EntityManagerFactoryUtils.java:221)
at org.springframework.orm.jpa.SharedEntityManagerCreator$SharedEntityManagerInvocationHandler.invoke(SharedEntityManagerCreator.java:255)
at com.sun.proxy.$Proxy42.createQuery(Unknown Source)
at gov.nih.nci.cbiit.scimgmt.idp.dao.LookupDao.findById(LookupDao.java:52)
at gov.nih.nci.cbiit.scimgmt.idp.dao.LookupDao$$FastClassBySpringCGLIB$$7b0b6cbb.invoke(<generated>)
at org.springframework.cglib.proxy.MethodProxy.invoke(MethodProxy.java:204)
at org.springframework.aop.framework.CglibAopProxy$DynamicAdvisedInterceptor.intercept(CglibAopProxy.java:651)
at gov.nih.nci.cbiit.scimgmt.idp.dao.LookupDao$$EnhancerBySpringCGLIB$$1cd8b9dd.findById(<generated>)
at gov.nih.nci.cbiit.scimgmt.idp.service.impl.LookupServiceImpl.findById(LookupServiceImpl.java:21)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
转换后的支持 JPA 的 DAO 类,只有 1 个方法:
public class LookupDao {
private final Logger log = LogManager.getLogger(getClass());
@PersistenceContext
private EntityManager entityManager;
public LookupT findById(long id) throws Exception {
log.info("Entered: LookupDao.findById(), id = " + id);
// Pre-JPA (pre-conversion; note: commented out. No Hibernate Session conflicts)
// -------
/*
log.info("getting lookup id="+id);
return sessionFactory.getCurrentSession().get(LookupT.class, id);
*/
// New JPA Approach (converted)
// ----------------
CriteriaBuilder crbuilder = entityManager.getCriteriaBuilder();
CriteriaQuery<LookupT> crquery = crbuilder.createQuery(LookupT.class);
Root<LookupT> root = crquery.from(LookupT.class);
crquery.where(
(crbuilder.equal(root.get("id"), id))
);
Query q = entityManager.createQuery(crquery);
return (LookupT)q.getSingleResult();
}
图书馆:
- spring-aop-4.3.2.RELEASE.jar
- spring-beans-4.3.2.RELEASE.jar
- spring-context-4.3.2.RELEASE.jar
- spring-core-4.3.2.RELEASE.jar
- spring-jdbc-4.3.2.RELEASE.jar
- spring-web-4.3.2.RELEASE.jar
- hibernate-commons-annotations-5.0.1.Final.jar
- hibernate-core-5.2.1.Final.jar
- hibernate-jpa-2.1-api-1.0.0.Final.jar
还有什么对调试有帮助的吗?
我已经确认:
- Hibernate Session 和 EntityManager 之间没有混合,只有 1 个 DAO 使用 EntityManager 的 1 种方法,其他所有内容均已注释 出去。
- 不使用 Spring-Boot
【问题讨论】: