且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

我如何获得会话对象,如果我有entitymanager

更新时间:2022-10-23 22:25:23

为了完全穷尽,如果您使用JPA 1.0或JPA 2.0执行。

JPA 1.0



使用JPA 1.0,您必须使用 EntityManager#getDelegate() 。但请记住, 此方法的结果是特定于实现的 ,即从使用Hibernate的应用程序服务器不可移植到另一个。例如使用JBoss 你会这样做:

  org.hibernate.Session session =(Session)manager.getDelegate(); 

,你必须这样做:

  org.hibernate.Session session =((org.hibernate.ejb.EntityManagerImpl)em.getDelegate())。getSession(); 

我同意,这太可怕了,规范应该归咎于这里(不够清楚)使用JPA 2.0,有一个新的(并且更好的) EntityManager#unwrap(Class< T>) 方法,该方法优先于 EntityManager#getDelegate() 用于新应用程序。



因此,使用Hibernate作为JPA 2.0实现(参见 3.15。原生Hibernate API ),您应该这样做:

 会话会话= entityManager.unwrap(Session.class ); 


I have

private EntityManager em;

public List getAll(DetachedCriteria detachedCriteria)   {

    return detachedCriteria.getExecutableCriteria( ??? ).list();
}

How can i retrieve the session if am using entitymanager or how can i get the result from my detachedcriteria ?

To be totally exhaustive, things are different if you're using a JPA 1.0 or a JPA 2.0 implementation.

JPA 1.0

With JPA 1.0, you'd have to use EntityManager#getDelegate(). But keep in mind that the result of this method is implementation specific i.e. non portable from application server using Hibernate to the other. For example with JBoss you would do:

org.hibernate.Session session = (Session) manager.getDelegate();

But with GlassFish, you'd have to do:

org.hibernate.Session session = ((org.hibernate.ejb.EntityManagerImpl) em.getDelegate()).getSession(); 

I agree, that's horrible, and the spec is to blame here (not clear enough).

JPA 2.0

With JPA 2.0, there is a new (and much better) EntityManager#unwrap(Class<T>) method that is to be preferred over EntityManager#getDelegate() for new applications.

So with Hibernate as JPA 2.0 implementation (see 3.15. Native Hibernate API), you would do:

Session session = entityManager.unwrap(Session.class);