HIbernate中openSession和getCurrentSession

  这两者的差别网上非常多资源,我这里就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();
        }
    }

  可能比較片面。可是眼下还没有到那个层面,慢慢来,就像之前看这两个的差别一样。一直看不懂。慢慢的积累到一定层度就会非常好理解了。

posted @ 2017-06-20 19:53  claireyuancy  阅读(628)  评论(0编辑  收藏  举报