zoukankan      html  css  js  c++  java
  • 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();
            }
        }

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

  • 相关阅读:
    【题解】Luogu P4391 [BOI2009]Radio Transmission 无线传输
    kmp匹配详解
    点分治详解
    【题解】Luogu P3871 [TJOI2010]中位数
    树链剖分详解
    【题解】Luogu P3901 数列找不同
    【题解】Luogu P1503 鬼子进村
    【题解】 P2234 [HNOI2002]营业额统计
    Splay详解
    JSOI2020备考知识点复习
  • 原文地址:https://www.cnblogs.com/claireyuancy/p/7056030.html
Copyright © 2011-2022 走看看