如果我有实体管理器,如何获取会话对象 [英] How can i get the session object if i have the entity-manager
问题描述
我有
private EntityManager em;
public List getAll(DetachedCriteria detachedCriteria) {
return detachedCriteria.getExecutableCriteria("....").list();
}
如果使用的是entitymanager,如何检索会话?如何从分离的条件中获取结果?
How can I retrieve the session if am using entitymanager or how can I get the result from my detached criteria?
推荐答案
要详尽无遗,如果您使用的是JPA 1.0或JPA 2.0实现,情况会有所不同.
To be totally exhaustive, things are different if you're using a JPA 1.0 or a JPA 2.0 implementation.
对于JPA 1.0,您必须使用 EntityManager#getDelegate()
.但是请记住, 此方法的结果是特定于实现的 ,即从使用Hibernate的应用程序服务器到另一台服务器之间不可移植.例如,使用JBoss 你会做的:
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();
但是使用GlassFish ,您必须这样做:
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,有了一个新的(更好的) EntityManager#getDelegate()
用于新应用程序.
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.
因此将Hibernate作为JPA 2.0实现(请参见 3.15.本机Hibernate API ),您可以这样做:
So with Hibernate as JPA 2.0 implementation (see 3.15. Native Hibernate API), you would do:
Session session = entityManager.unwrap(Session.class);
这篇关于如果我有实体管理器,如何获取会话对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!