zoukankan      html  css  js  c++  java
  • Hibernate getCurrentSession()和openSession()的区别

    1. 通过getCurrentSession()创建的Session会绑定到当前线程上;openSession()不会。
    2. 通过getCurrentSession()获取Session,首先是从当前上下文中寻找旧的Session,如果没有,则创建新的Session;而openSession()是每次都创建新的Session。
    3. getCurrentSession()创建的Session在事物提交时自动关闭;openSession()创建的Session需要手动关闭。
       1     @Test
       2     public void testTeacherSave() {
       3     
       4         Teacher t = new Teacher();
       5         
       6         t.setName("t1");
       7         t.setTitle("middle");
       8         t.setBirthDate(new Date());
       9         
      10         Session session = sessionFactory.openSession();
      11         //Session session = sessionFactory.getCurrentSession();
      12         
      13         session.beginTransaction();
      14         session.save(t);
      15         
      16         Session session2 = sessionFactory.getCurrentSession();
      17         
      18         System.out.println(session == session2);
      19         
      20         session.getTransaction().commit();
      21         
      22         Session session3 = sessionFactory.getCurrentSession();
      23         
      24         System.out.println(session == session3);
      25         
      26     }

      输出:Hibernate:
          insert
          into
              Teacher
              (birthDate, gender, good, name, title)
          values
              (?, ?, ?, ?, ?)
      false
      false

       1 @Test
       2     public void testTeacherSave() {
       3     
       4         Teacher t = new Teacher();
       5         
       6         t.setName("t1");
       7         t.setTitle("middle");
       8         t.setBirthDate(new Date());
       9         
      10         //Session session = sessionFactory.openSession();
      11         Session session = sessionFactory.getCurrentSession();
      12         
      13         session.beginTransaction();
      14         session.save(t);
      15         
      16         Session session2 = sessionFactory.getCurrentSession();
      17         
      18         System.out.println(session == session2);
      19         
      20         session.getTransaction().commit();
      21         
      22         Session session3 = sessionFactory.getCurrentSession();
      23         
      24         System.out.println(session == session3);
      25         
      26     }

      输出:Hibernate:
          insert
          into
              Teacher
              (birthDate, gender, good, name, title)
          values
              (?, ?, ?, ?, ?)
      true
      false

  • 相关阅读:
    读《程序是怎样跑起来的》第七章有感
    读《程序是怎样跑起来的》第六章有感
    读《程序是怎样跑起来的》第五章有感
    读《程序是怎样跑起来的》第四章有感
    读《程序是怎样跑起来的》第三章有感
    读《怎样成为一个高手 183》有感
    读《程序是怎样跑起来的》第二章有感
    《程序是怎样跑起来的》第一章读后感
    我与计算机
    师生关系
  • 原文地址:https://www.cnblogs.com/ming-zi/p/5937961.html
Copyright © 2011-2022 走看看