我们正在使用Hibernate作为JPA提供程序开发Java EE应用程序。我们现在希望使用Hibernate Criterias,但为此我需要访问HibernateEntityManagerImpl。
我们目前在componentContext.xml
中有这个 <context:component-scan base-package="com.volvo.it.lsm"/>
<!-- JPA EntityManagerFactory -->
<bean id="EmployeeDomainEntityManagerFactory" parent="hibernateEntityManagerFactory" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
<property name="persistenceUnitName" value="EmployeeDomainPU" />
</bean>
在我们的课程中:
@PersistenceContext(unitName = "EmployeeDomainPU")
public void setEntityManager(EntityManager em) {
this.em = em;
}
谢谢!
答案 0 :(得分:2)
EntityManager em ...
//if you want Session with JPA 1.0
org.hibernate.Session session = (org.hibernate.Session) em.getDelegate();
//If you use JPA 2.0 this is preferred way
org.hibernate.Session session2 = em.unwrap(org.hibernate.Session.class);
//if you really want Hibernates implementation of EntityManager, just cast
//it (this is not needed for Criteria queries though). Actual implementing class
//is of course Hibernates business and it can vary
org.hibernate.ejb.EntityManagerImpl emi =
(org.hibernate.ejb.EntityManagerImpl) em;
答案 1 :(得分:1)
使用此代码:
Session session = (Session) entityManager.getDelegate();
session.createCriteria(...);
请注意,JPA2也有(不同的)Criteria API。使用IMHO更难,但它更安全,并且具有与Hibernate Criteria API相同的优点(能够动态组合查询)
答案 2 :(得分:0)
您可以调用em.getDelegate()并将其强制转换为Hibernate类