zoukankan      html  css  js  c++  java
  • Hibernate(八)--session的两种获取方式


    openSession
    getCurrentSession

    Hibernate有两种方式获得session,分别是:
      openSession和getCurrentSession
    他们的区别在于
    1. 获取的是否是同一个session对象
      openSession每次都会得到一个新的Session对象
      getCurrentSession在同一个线程中,每次都是获取相同的Session对象,但是在不同的线程中获取的是不同的Session对象

          SessionFactory factory=new Configuration().configure().buildSessionFactory();
    
            Session session = factory.openSession();
            Session session1= factory.openSession();
            System.out.println(session==session1);
    

    同一线程:主线程(true) Session session2 = factory.getCurrentSession(); Session session3= factory.getCurrentSession(); System.out.println(session2==session3);

    不同线程: (false)

    public class Test {
        static Session s1;
        static Session s2;
    
        public static void main(String[] args) throws InterruptedException {
    
            final SessionFactory sf = new Configuration().configure().buildSessionFactory();
    
            Thread t1 = new Thread() {
                public void run() {
                    s1 = sf.getCurrentSession();
                }
            };
            t1.start();
    
            Thread t2 = new Thread() {
                public void run() {
                    s2 = sf.getCurrentSession();
                }
            };
            t2.start();
            t1.join();
            t2.join();
    
            System.out.println(s1 == s2);
        }
    }


    2. 事务提交的必要性
      openSession只有在增加,删除,修改的时候需要事务,查询时不需要的(get方法)
      getCurrentSession是所有操作都必须放在事务中进行,并且提交事务后,session就自动关闭,不能够再进行关闭

     

     提交事务后,session就自动关闭,不能够再进行关闭:

  • 相关阅读:
    腾讯新闻评论数据爬取
    腾讯新闻评论数据爬取
    腾讯新闻评论数据爬取
    Storm系统架构以及代码结构学习
    Storm系统架构以及代码结构学习
    Storm系统架构以及代码结构学习
    网络新闻评论观点挖掘系统实现
    网络新闻评论观点挖掘系统实现
    网络新闻评论观点挖掘系统实现
    Confluence 6 配置验证码(Captcha)来防止垃圾
  • 原文地址:https://www.cnblogs.com/crazy-lc/p/12242440.html
Copyright © 2011-2022 走看看