hibernate获取session的两种方式的区别

来源:互联网 发布:移动网络ip地址是什么 编辑:程序博客网 时间:2024/05/22 13:34

hibernate获取session有两种方式,存在着一定的区别

获取session的三个步骤

// 1.创建Configuration,该对象用于读取hibernate.cfg.xml,并完成初始化
    Configuration configuration = new Configuration().configure();


// 2.创建SessionFactory
    SessionFactory sessionFactory = configuration.buildSessionFactory();


// 3.创建Session,相当于jdbc的Connection

    Session session = sessionFactory.getCurrentSession();

或者Session session = sessionFactory.openSession();



区别如下:

①getCurrentSession()

这种方式获取到的session是与当前线程绑定的,是一个单例,且会自动关闭,如果再手动调用session.close()会报错。使用该单例session进行crud操作时必须开启事务,否则无法提交

   getCurrentSession()内部实际上调用了openSession()

使用该方式还需要进行配置文件,在hibernate.cfg.xml中添加

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


②openSession()

这种方式获取的session需要手动关闭,在进行crud操作时,如果只是进行查询操作则无需开启事务,进行增删改时必须开启事务

原创粉丝点击