hibernate中的SessionFactory的openSession与getCurrentSession

hibernate在得到session的方法中,openSession与getCurrentSession方法的区别?

        Configuration cfg = new AnnotationConfiguration();
        SessionFactory sf = cfg.configure().buildSessionFactory();
        Session session = sf.openSession();
        session.beginTransaction();
        session.getTransaction().commit();
        System.out.println(session);
        session.close();

        Configuration cfg = new AnnotationConfiguration();
        SessionFactory sf = cfg.configure().buildSessionFactory();
        Session session = sf.getCurrentSession();
        session.beginTransaction();
        session.getTransaction().commit();
        System.out.println(session);
  • opensession每次都打开一个新的session,而且在事物结束后,不会自动关闭,所以要手动关闭,即session.close();但是使用getcurrentsession获得的session就是从session的上下文中去寻找已经存在的session,如果上下文中没有,那么就创建一个新的,而且在事物执行完毕是,会自动关闭session。
  • 加入一件事物,既要数据库进行操作有要记录日志,那么这两个事务需要同时执行,我们知道事务的结束和开始,是以connection为标志的。所以这两件事应该使用同一个session,属于同一个事物,所以应该使用getcurrentsession获得session。
  • 另外需要注意:如果使用getcurrentsession需要配置以下信息
    
    <property name="current_session_context_class">threadproperty>
如果没有配置,会出现以下错误:
Exception in thread "main" org.hibernate.HibernateException: No CurrentSessionContextconfigured!atorg.hibernate.impl.SessionFactoryImpl.getCurrentSession(SessionFactoryImpl.java:572)
at com.test.SessionTest.main(SessionTest.java:25)

你可能感兴趣的:(hibernate中的SessionFactory的openSession与getCurrentSession)