加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Java > 正文

Hibernate之openSession与getCurrentSession的区别

发布时间:2020-12-15 07:13:43 所属栏目:Java 来源:网络整理
导读:openSession 与 getCurrentSession的区别 (1)openSession 每一次获得的是一个全新的session对象,而getCurrentSession获得的是与当前线程绑定的session对象; (2)openSession不需要配置,而getCurrentSession需要配置 property name="current_session_context

openSession 与 getCurrentSession的区别
(1)openSession 每一次获得的是一个全新的session对象,而getCurrentSession获得的是与当前线程绑定的session对象;
(2)openSession不需要配置,而getCurrentSession需要配置

<property name="current_session_context_class">thread</property> 

(3)openSession需要手动关闭,而getCurrentSession系统自动关闭

openSession出来的session要通过:session.close(),而getSessionCurrent出来的session系统自动关闭,如果自己关闭会报错

(4)Session是线程不同步的,要保证线程安全就要使用getCurrentSession

?

下面这段代码运行后可比较它们的(1)

package cn.blog.test;

import org.hibernate.Session;
 org.hibernate.SessionFactory;
 org.hibernate.cfg.Configuration;

public class Test {

    
//openSession与getCurrentSession对比

         static void main(String[] args) {  
              
                Configuration configuration = new Configuration().configure();  
                SessionFactory sf = configuration.buildSessionFactory();  
                  
                Session sessionOpen1 = sf.openSession();  
                Session sessionOpen2 = sf.openSession();  
                  
                Session sessionThread1 = sf.getCurrentSession();  
                Session sessionThread2 = sf.getCurrentSession();  
                  
                System.out.println(sessionOpen1.hashCode() + "<-------->" + sessionOpen2.hashCode());  每次创建都是新的session对象
                System.out.println(sessionThread1.hashCode() + "<-------->" + sessionThread2.hashCode());  每次获得的是当前session
    
}
         
}

?

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读