zoukankan      html  css  js  c++  java
  • hibernate下Session的获取方式

    Session是应用程序与数据库之间的一个会话,其重要性不言而喻。初学Hibernate,使用SessionFactory,老老实实地打开事务,提交,回滚,关闭session。

    1、直接通过SessionFactory构建Session对象(用openSession()或者getCurrentSession()),例子如下:

    try {
    SessionFactory sf =
    new Configuration().configure().buildSessionFactory();
    Session session = sf.openSession();

    //也可用 sf.getCurrentSession();区别在于前者每次都创建一个新的Session,而后者在当前无Session时才创建,否则会绑定到当前已有线程;前者必须手动关闭,后者在事务结束后自动关闭。

    Transaction tx = session.beginTransaction();

    。。。。

    。。。。

    。。。。

    若干操作

    tx.commit();
    session.close();

    } catch (HibernateException e) {
    e.printStackTrace();
    }
    }
    }

    后来,由于这样做太过繁琐每一步都得自行建立,因此引入spring管理Session。sessionfactory的创建等都交给spring管理.用户可以不再考虑session的管理,事务的开启关闭.只需配置事务即可.

    2、利用HibernateTemplate

    在applicationContext.xml中配置好相关事务,就可以很方便地获取Session了。

    @Autowired 

    HibernateTemplate hibernateTemplate;

    Session session=hibernateTemplate.getSessionFactory().openSession();

    3、利用HibernateCallback()接口中的doInHibernate方法

    this.getHibernateTemplate().execute(new HibernateCallback() {
    public Object doInHibernate(Session session) throws HibernateException{
    do something;
    }
    });

    在Spring+Hibernate环境中,推荐用这种方式来获取session。这种方法的优势在于你不需要对session进行维护,会由Spring管理。你只需在需要session环境时,调用即可。


  • 相关阅读:
    受限玻尔兹曼机 视频
    android textview空格占位符以及一些其他占位符汇总
    几种常见的Preference总结
    Android著名开源库
    Android 常用开源库总结(持续更新)
    2019最新Android常用开源库总结(附带github链接)
    Android gradle用exclude排除引用包中的dependency引用
    Gradle3.0新指令api、provided、implementation等对比
    jar包下载网站
    mac环境下Android 反编译
  • 原文地址:https://www.cnblogs.com/qcxdoit/p/5796370.html
Copyright © 2011-2022 走看看