在hibernate中有两种方法获得session
- openSession()
- getCurrentSession()
如果使用的getCurrentSession()方法 就要在hibernate.cfg.xml文件中进行配置
如果是本地事务(JDBC)
<property name="hibernate.current_session_context_class">thread</property>
如果是全局事物(jta)
<property name="hibernate.current_session_context_class">jta</property>
两种方法的区别
1.openSession()每次创建新的session对象,getCurrentSession()使用现有的session对象 (类似单例模式)
2.getCurrentSession在事务提交或者回滚之后会自动关闭,而openSession()需要手动关闭(session.close()),如果使用openSession()后未关闭,多次创建后会导致线程池溢出。
@Test
public void testOpenSession() {
//获得配置对象
Configuration config = new Configuration().configure();
//获得服务注册对象
ServiceRegistry serviceRegistry = new ServiceRegistryBuilder()
.applySettings(config.getProperties()).buildServiceRegistry();
//获得session工厂对象
SessionFactory sessionFactory = config
.buildSessionFactory(serviceRegistry);
//获得session对象
Session session1 = sessionFactory.openSession();
Session session2 = sessionFactory.openSession();
System.out.println(session1 == session2);//false
}
@Test
public void testGetCurrentSession() {
//获得配置对象
Configuration config = new Configuration().configure();
//获得服务注册对象
ServiceRegistry serviceRegistry = new ServiceRegistryBuilder()
.applySettings(config.getProperties()).buildServiceRegistry();
//获得session工厂对象
SessionFactory sessionFactory = config
.buildSessionFactory(serviceRegistry);
//获得session对象
Session session1 = sessionFactory.getCurrentSession();
Session session2 = sessionFactory.getCurrentSession();
System.out.println(session1 == session2);//true
}