JPA EntityManager获得session、connection

来源:互联网 发布:淘宝皇冠蓝冠 编辑:程序博客网 时间:2024/05/13 23:34

原文转载自:http://blog.csdn.net/earthhour/article/details/17220831

1、获得Hibernate Session

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

2、获得java.sql.Connection

方法1:

JPA 2.0
entityManager.getTransaction().begin();
java.sql.Connection connection = entityManager.unwrap(java.sql.Connection.class);
...
entityManager.getTransaction().commit();

但是对于Hibernate3.6.5会报错PersistenceException包含如下信息:Hibernate cannot unwrap interface java.sql.Connection

方法2:

SessionImplementor session =entityManager.unwrap(SessionImplementor.class);
session.connection();

方法3:

Session session = (org.hibernate.Session) em.getDelegate();
SessionFactoryImplementor sf = (SessionFactoryImplementor) session.getSessionFactory();
connection  = sf.getConnectionProvider().getConnection();

hibenate 4.3 :

Session session = (Session) em.getDelegate();
SessionFactoryImpl sessionFactory = (SessionFactoryImpl) session.getSessionFactory();
connection = sessionFactory.getConnectionProvider().getConnection();

-----------------------------------------------分割线---------------华丽丽--------------------------------------------------------------------------

JPA 与Hibernate

Hibernate:是一个对象持久化框架,简化了 Java 应用程序和底层关系数据库之间的对象关系映射。方法是提供 POJO 的透明持久化,作为“中介”层来提供自动持久化,并从 Java 应用程序加载对象到数据库表。借助 Hibernate,保存对象状态到数据库和从数据库加载对象状态与调用 Java 对象中的方法一样容易。

JPA :Java Persistence API,是Java EE 5的标准ORM接口,也是ejb3规范的一部分。

Hibernate:当今很流行的ORM框架,是JPA的一个实现,但是其功能是JPA的超集。

JPA和Hibernate之间的关系,可以简单的理解为JPA是标准接口,Hibernate是实现。还有其他ORM框架也实现了JPA规范。

1 0