hibernate 自身提供了三种管理Session对象的方法
Session 对象的生命周期与本地线程绑定
Session 对象的生命周期与JTA事务绑定
Hibernate 委托程序管理Session对象的生命周期
Session 对象的生命周期与本地线程绑定实示例
步骤:
1.hibernate.cfg.xml配置管理Session的方式
<!-- 配置管理 Session 的方式 --> <property name="current_session_context_class">thread</property>2.写一个Util类,使SessionFactory单例
public class HibernateUtils { private HibernateUtils(){} private static HibernateUtils instance = new HibernateUtils(); public static HibernateUtils getInstance() { return instance; } private SessionFactory sessionFactory; public SessionFactory getSessionFactory() { if (sessionFactory == null) { Configuration configuration = new Configuration().configure(); ServiceRegistry serviceRegistry = new ServiceRegistryBuilder() .applySettings(configuration.getProperties()) .buildServiceRegistry(); sessionFactory = configuration.buildSessionFactory(serviceRegistry); } return sessionFactory; } public Session getSession(){ return getSessionFactory().getCurrentSession(); } }
3.DAO层调用
public class DepartmentDao { public void save(Department dept){ //内部获取 Session 对象 //获取和当前线程绑定的 Session 对象 //1. 不需要从外部传入 Session 对象 //2. 多个 DAO 方法也可以使用一个事务! Session session = HibernateUtils.getInstance().getSession(); System.out.println(session.hashCode()); session.save(dept); } }
4.测试类:
@Test public void testManageSession(){ //获取 Session //开启事务 Session session = HibernateUtils.getInstance().getSession(); Transaction transaction = session.beginTransaction(); DepartmentDao departmentDao = new DepartmentDao(); Department dept = new Department(); dept.setName("ATGUIGU"); departmentDao.save(dept); //若 Session 是由 thread 来管理的, 则在提交或回滚事务时, 已经关闭 Session 了. transaction.commit(); System.out.println(session.isOpen()); }
说明:
1.当一个线程(threadA)第一次调用SessionFactory对象的getCurrentSession()方法时,该方法会创建一个新的Session(sessionA)对象,把该对象与threadA绑定,并将sessionA返回
2.当 threadA再次调用SessionFactory对象的getCurrentSession()方法时,该方法将返回sessionA对象
3.当 threadA提交sessionA对象关联的事务时,Hibernate 会自动flushsessionA对象的缓存,然后提交事务,关闭sessionA对象.
当threadA撤销sessionA对象关联的事务时,也会自动关闭sessionA对象
4.若 threadA再次调用SessionFactory对象的getCurrentSession()方法时,该方法会又创建一个新的Session(sessionB)对象,把该对象与threadA绑定,并将sessionB返回