如果我有实体管理器,如何获取会话对象? [英] How can I get the session object if I have the entity-manager?

查看:55
本文介绍了如果我有实体管理器,如何获取会话对象?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有

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,就有了一个新的(更好的)

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆