Hibernate openSession() 和 getCurrentSession的區別
getHiberanteTemplate 、getCurrentSession和OpenSession
采用getCurrentSession()創建的Session會綁定到當前的線程中去、而采用OpenSession()則不會。
采用getCurrentSession()創建的Session在commit或rollback后會自動關閉,采用OpenSession()必須手動關閉。
采用getCurrentSession()需要在Hibernate.cfg.xml配置文件中加入如下配置:
如果是本地事物,及JDBC一個數據庫:
<propety name=”Hibernate.current_session_context_class”>thread</propety>
如果是全局事物,及jta事物、多個數據庫資源或事物資源:
<propety name=”Hibernate.current_session_context_class”>jta</propety>
使用spring的getHiberanteTemplate 就不需要考慮事務管理和session關閉的問題:
public List getEntityCriteria(final DetachedCriteria detachedCriteria) {
return (List) getHibernateTemplate().executeFind(
new HibernateCallback() {
public Object doInHibernate(Session session)
throws HibernateException {
Criteria criteria = detachedCriteria
.getExecutableCriteria(session);
return criteria.list();
}
});
}
public List getEntityCriteriaByPage(final DetachedCriteria detachedCriteria,final Page page) {
return (List) getHibernateTemplate().executeFind(
new HibernateCallback() {
public Object doInHibernate(Session session)
throws HibernateException {
Criteria criteria = detachedCriteria
.getExecutableCriteria(session);
criteria.setFirstResult(page.getFirstItemPos());
criteria.setMaxResults(page.getPageSize());
return criteria.list();
}
});
}
DetachedCriteria detachedCriteria = DetachedCriteria.forClass(Department.class);
detachedCriteria.add(Restrictions.eq("eid", seacher.getEid()));//企業id為條件查詢
detachedCriteria.add(Restrictions.in("dprtid", ids));//根據id數組查詢部門
detachedCriteria.add(Restrictions.like("name", "%" + seacher.getName()+ "%"));//名稱模糊查詢
getEntityCriteriaByPage(detachedCriteria,pageinfo);
經過檢查激活連接為0,被使用的連接總是為1(應為自己測試)
package com.myj.hibernate.model;
import org.hibernate.HibernateException;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.AnnotationConfiguration;
import org.hibernate.classic.Session;
import org.junit.AfterClass;
import org.junit.BeforeClass;
import org.junit.Test;
public class TeacherTest {
public static SessionFactory sessionFactory = null;
@BeforeClass
public static void beforeClass() {
try {
sessionFactory = new AnnotationConfiguration().configure().buildSession Factory();
} catch (HibernateException e) {
e.printStackTrace();
}
}
@Test
public void testTeacherSave() {
Teacher teacher = new Teacher();
teacher.setName("martian");
teacher.setAge(23);
Session session = sessionFactory.getCurrentSession();
session.beginTransaction();
session.save(teacher);
//測試getCurrentSession()方法,這里輸出true,因為在一個事務內,所以取得線程中的session
Session session1 = sessionFactory.getCurrentSession();
System.out.println(session == session1);
//commit()之后不用close(),假如使用sessionFactory.openSession();就需要close();
session.getTransaction().commit();
//測試getCurrentSession()方法,這輸出false,上一個事務已經提交,這里將重新生成一個session
Session session2 = sessionFactory.getCurrentSession();
System.out.println(session == session2);
}
@AfterClass
public static void afterClass() {
sessionFactory.close();
}
}
