管理Session
1:把session和本地线程绑定在一起。
1):创建一个sessionFactory。然后由它去创建session
package com.hq.util; import org.hibernate.Session; import org.hibernate.SessionFactory; import org.hibernate.cfg.Configuration; import org.hibernate.service.ServiceRegistry; import org.hibernate.service.ServiceRegistryBuilder; 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(); } }
使用:getCurrentSession()方法。
2):通过单例的HibernateUtils来得到session
public class DeptDao { public void save(Department dept){ Session session=HibernateUtils.getInstance().getSession(); System.out.println(session.hashCode()); // session.save(dept); } }
3):在配置文件中配置
<!-- 配置管理session的方法 --> <property name="current_session_context_class">thread</property>
4):测试
@org.junit.Test public void testSession(){ //获取 Session //开启事务 Session session = HibernateUtils.getInstance().getSession(); System.out.println("-->" + session.hashCode()); Transaction transaction = session.beginTransaction(); DeptDao departmentDao = new DeptDao(); Department dept = new Department(); dept.setName("ATGUIGU"); departmentDao.save(dept); departmentDao.save(dept); departmentDao.save(dept); //若 Session 是由 thread 来管理的, 则在提交或回滚事务时, 已经关闭 Session 了. transaction.commit(); System.out.println(session.isOpen()); }