hibernate两种获取session方法的区别

在hibernate中有两种方法获得session

  1. openSession()
  2. 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
	}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值