Session是應用程序與數據庫之間的一個會話,其重要性不言而喻。初學Hibernate,使用SessionFactory,老老實實地打開事務,提交,回滾,關閉session。
1、直接通過SessionFactory構建Session對象(用openSession()或者getCurrentSession()),例子如下:
try {
SessionFactory sf =
new Configuration().configure().buildSessionFactory();
Session session = sf.openSession();
//也可用 sf.getCurrentSession();區別在於前者每次都創建一個新的Session,而后者在當前無Session時才創建,否則會綁定到當前已有線程;前者必須手動關閉,后者在事務結束后自動關閉。
Transaction tx = session.beginTransaction();
。。。。
。。。。
。。。。
若干操作
tx.commit();
session.close();
} catch (HibernateException e) {
e.printStackTrace();
}
}
}
后來,由於這樣做太過繁瑣每一步都得自行建立,因此引入spring管理Session。sessionfactory的創建等都交給spring管理.用戶可以不再考慮session的管理,事務的開啟關閉.只需配置事務即可.
2、利用HibernateTemplate
在applicationContext.xml中配置好相關事務,就可以很方便地獲取Session了。
@Autowired
HibernateTemplate hibernateTemplate;
Session session=hibernateTemplate.getSessionFactory().openSession();
3、利用HibernateCallback()接口中的doInHibernate方法
this.getHibernateTemplate().execute(new HibernateCallback() {
public Object doInHibernate(Session session) throws HibernateException{
do something;
}
});
在Spring+Hibernate環境中,推薦用這種方式來獲取session。這種方法的優勢在於你不需要對session進行維護,會由Spring管理。你只需在需要session環境時,調用即可。
