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();
        }
    }

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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值