Hibernate getCurrentSession()和openSession()的区别

时间:2021-07-23 08:33:32
  1. 通过getCurrentSession()创建的Session会绑定到当前线程上;openSession()不会。
  2. 通过getCurrentSession()获取Session,首先是从当前上下文中寻找旧的Session,如果没有,则创建新的Session;而openSession()是每次都创建新的Session。
  3. getCurrentSession()创建的Session在事物提交时自动关闭;openSession()创建的Session需要手动关闭。
         @Test
    public void testTeacherSave() { Teacher t = new Teacher(); t.setName("t1");
    t.setTitle("middle");
    t.setBirthDate(new Date()); Session session = sessionFactory.openSession();
    //Session session = sessionFactory.getCurrentSession(); session.beginTransaction();
    session.save(t); Session session2 = sessionFactory.getCurrentSession(); System.out.println(session == session2); session.getTransaction().commit(); Session session3 = sessionFactory.getCurrentSession(); System.out.println(session == session3); }

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

     @Test
    public void testTeacherSave() { Teacher t = new Teacher(); t.setName("t1");
    t.setTitle("middle");
    t.setBirthDate(new Date()); //Session session = sessionFactory.openSession();
    Session session = sessionFactory.getCurrentSession(); session.beginTransaction();
    session.save(t); Session session2 = sessionFactory.getCurrentSession(); System.out.println(session == session2); session.getTransaction().commit(); Session session3 = sessionFactory.getCurrentSession(); System.out.println(session == session3); }

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