Hibernate辅助类是用来负责启动 Hibernate 和方便地操作org.hibernateSessionFactory
- import org.hibernate.SessionFactory;
- import org.hibernate.cfg.Configuration;
- public class HibernateUtil {
- private static final SessionFactory sessionFactory ;
- static{
- // Create the SessionFactory from hibernate.cfg.xml
- sessionFactory = new Configuration().configure().buildSessionFactory();
- }
- private static SessionFactory buildSessionFactory() {
- return sessionFactory;
- }
- public static SessionFactory getSessionFactory() {
- return sessionFactory;
- }
- }
只要你持有 org.hibernate.SessionFactory
,大可在任何时候、任何地点调用这个方法getCurrentSession()
方法
总会返回“当前的”工作单元session
Hibernate 提供三种跟踪当前会话的方法。基于“线程”的方法不适合于产品环境,它仅用于 prototyping 和教学用途。后面将更详细地讨论会话跟踪。
session的生命周期
Session 在第一次被使用的时候,即第一次调用 getCurrentSession()
的时候,其生命周期就开始。然后它被 Hibernate 绑定到当前线程。当事务结束的时候,不管是提交还是回滚,Hibernate 会自动把org.hibernate.Session 从当前线程剥离,并且关闭它。假若你再次调用getCurrentSession()
,你会得到一个新的org.hibernate.Session,并且开始一个新的工作单元。
Hibernate org.hibernate.Session 的生命周期可以很灵活。绝对不要把应用程序设计成为每一次数据库操作都用一个新的 Hibernate org.hibernate.Session。