Hibernate!!configuration类以及openSession和getCurrentSession的区别

Hibernate的configuration类:

configuration类是用来加载hibernate配置文件的,默认的是读取hibernate.cfg.xml配置文件的信息。

Configuration  cfg = new Configuration().configure();
//Configuration  cfg = new AnnotationConfiguration().configure();   //使用annotation的加载配置文件的方法
SessionFactory  sf = cfg.buildSessionFactory();
Session  session = sf.openSession();
//Session  session = sf.getCurrentSession();

SessionFactory

  • 用来产生和管理session
  • 通常情况下每个应用只需要一个SessionFactory
  • 除非要访问多个数据库的情况
  • 常用的两个方法是 openSession()和getCurrentSession()

openSession每次都是建立新的Session,此方法需要close;

getCurrentSession 是从上下文找,如果有,用旧的,如果没有,就建立新的Session,

 此用途是建立事务边界,此方法是事务提交后自动close;

此方法和在hibernate.cfg.xml的配置属性有关,是:

hibernate.current_Session_context_class属性,可取的值有:jta  |   thread  |  managed  |  custom.class

  • current_Session_context_class (jta  thread )(Java transaction api)!!和Java persistence api jpa别混淆了

可以自己写一个SessionFactory的工具类

public class HibernateUtil {
    private  static  SessionFactory  factory = null;
    //静态块
    static{
        try {
            //加载hibernate的配置文件
            Configuration  cfg = new Configuration().configure();
            
            //实例化sessionFactory
            factory = cfg.buildSessionFactory() ;
        } catch (HibernateException e) {
            // TODO: handle exception
            e.printStackTrace() ;
        }
    }
    
    /**
     * 获取Session对象
     * @return Session 对象
     */
    public  static Session  getSession(){
        //如果sessionfactory不为空,则开启session
        Session  session = (factory != null) ? factory.openSession() : null ;
        return session ;
    }
    
    public static SessionFactory getSessionFactory() {
        return factory;
    }
    
    public  static  void  closeSession(Session session){
        if(session != null){
            if(session.isOpen()){
                session.close() ;//关闭session
            }
        }
    }
}

用getCurrentSession 需要设置Session的上下文,上下文有两种,第一种是jta,第二种是thread

 thread主要是从数据库建立它的事务,jta是从分布式,jta运行时需要application server的支持。

!!#!!关于多个事务

JTATransactionManager

事务有两种:一种是依赖数据库本身的简单事务,我们称之为connection事务

第二种是JTA事务

~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

写于2014年12月21日,关于用getCurrentSession(),忘记在hibernate.cfg.xml  中配置

在集成Hibernate的环境下(例如Jboss),要在hibernate.cfg.xml中session-factory段加入:

 1 <property name="current_session_context_class">jta</property>  

在不集成Hibernate的环境下(例如使用JDBC的独立应用程序),在hibernate.cfg.xml中session-factory段加入:

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

原文地址:https://www.cnblogs.com/Mokaffe/p/4151289.html