2011-10-11 16 views
0

我們正在開發一個使用Hibernate作爲JPA提供程序的Java EE應用程序。我們現在希望使用Hibernate Criterias,但爲此我需要訪問HibernateEntityManagerImpl。Hibernate EntityManagerImpl:獲取或設置對它的訪問

我們在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; 
} 

謝謝!

回答

1

使用此代碼:

Session session = (Session) entityManager.getDelegate(); 
session.createCriteria(...); 

注意JPA2有一個(不同的)標準API爲好。使用恕我直言很難,但它更加類型安全,並且與Hibernate Criteria API具有相同的優點(能夠動態地組成查詢)

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; 
相關問題