您的位置:首页 > 运维架构

HIbernate中openSession和getCurrentSession

2015-07-14 17:00 363 查看
  这两者的区别网上很多资源,我这里就copy一下了,然后有点问题的是今天遇到的问题。

  openSession和getCurrentSession的根本区别在于有没有绑定当前线程,所以,使用方法有差异:

* openSession没有绑定当前线程,所以,使用完后必须关闭,

* currentSession和当前线程绑定,在事务结束后会自动关闭。

  今天在复习Hibernate时,看到Hibernate检索方式的时候,写了一个小例子:

@Test
    public void query01() {
        SessionFactory sessionFactory = new Configuration().configure()
                .buildSessionFactory();
        Session session = sessionFactory.getCurrentSession();
        /*
         * 使用getCurrentSession()必须开启事物,否则抛出异常org.hibernate.HibernateException:
         * createQuery is not valid without active transaction
         */
        session.beginTransaction();
        Query query = session.createQuery("from Employee");
        System.out.println(query.list());
    }


  hibernate.cfg.xml中配置了

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


  这里已经写了注释,我遇到的问题就是这个,在进行查询的时候使用getCurrentSession竟然抛出 createQuery is not valid without active transaction的异常,觉得很奇怪。

  按照文档说:getCurrentSession()方法获取Session的机制应该是

“在getCurrentSession() 被调用的时候,实际被执行的方法是CurrentSessionContext.currentSession() 。在currentSession() 执行时,如果当前 Session为空,currentSession会调用 SessionFactory 的 openSession。”

  现在的状态是符合Session为空的情况,那么就应该通过openSession()方法产生一个Session,但是却抛出了异常。

  Google了一下,找到一篇博文:http://liusu.iteye.com/blog/380397

  里面介绍了关于这个问题,英文有点水,理解就看自己了。

  我的感觉就是出现这种情况感觉openSession相对来说还好用一些了。

@Test
    public void query02() {
        SessionFactory sessionFactory = new Configuration().configure()
                .buildSessionFactory();
        Session session = sessionFactory.openSession();;
        try {
            Query query = session.createQuery("from Employee");
            System.out.println(query.list());
        } catch (HibernateException e) {
            e.printStackTrace();
        }finally{
            session.close();
        }
    }


  可能比较片面,但是目前还没有到那个层面,慢慢来,就像之前看这两个的区别一样,一直看不懂,慢慢的积累到一定层度就会很好理解了。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: