hibernate两种获取session方法的区别

网友投稿 983 2022-09-01

hibernate两种获取session方法的区别

hibernate两种获取session方法的区别

在hibernate中有两种方法获得session

openSession()getCurrentSession()

如果使用的getCurrentSession()方法  就要在hibernate.cfg.xml文件中进行配置

如果是本地事务(JDBC)

thread

如果是全局事物(jta)

jta

两种方法的区别

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 }

版权声明:本文内容由网络用户投稿,版权归原作者所有,本站不拥有其著作权,亦不承担相应法律责任。如果您发现本站中有涉嫌抄袭或描述失实的内容,请联系我们jiasou666@gmail.com 处理,核实后本网站将在24小时内删除侵权内容。

上一篇:PHP路由技术的原理与实践(php 原理)
下一篇:PHP语言好不好?优势在哪里?(php语言好学吗)
相关文章

 发表评论

暂时没有评论,来抢沙发吧~