博客
关于我
Hibernate入门(五)---------事务管理
阅读量:423 次
发布时间:2019-03-06

本文共 1233 字,大约阅读时间需要 4 分钟。

  在Hibernate中,可以通过代码来操作管理事务,如通过“Transaction tx = session.beginTransaction()”,开启一个事务,持久化操作后,通过"tx.commit()",提交事务,如果事务出现异常又通过"tx.rollback()".操作来撤销事务(事务回滚)。

  除了在代码中对事务开启,提交和回滚操作外,还可以在Hibernate的配置文件中对事务进行配置,配置文件中,可以设置事务的隔离级别。其具体的配置方法是在hibernate.cfg.xml文件中的<session-factory>标签中进行的。配置方法如下:

  

如何保证在Service中开启事务时使用的Session对象和DAO中多个操作使用的是同一个Session对象。

  其实有两种办法可以实现:

    1.可以在业务层获取到Session,并将Session作为参数传递给DAO。

    2.可以使用ThreadLocal将业务层获取到的Session绑定到当前线程中,然后在DAO中获取Session的时候,都从当前线程中获取。

  其实使用第二种方式肯定是最优方案,那么具体的实现已经不用我们来完成了,Hibernate的内部已经将这个事情做完了。我们只需要完成一段配置即可。

  Hibernate5自身提供了三种管理Session对象的方法:

    Session对象的生命周期与本地线程绑定

    Session对象的生命周期与JTA事务绑定

    Hibernate委托程序管理Session对象的生命周期

  在Hibernate的配置文件中,hibernate current_session_context_class 属性用于指定Session管理方式 可选值包括:

    thread:Session 对象的生命周期与本地线程绑定。

    jta:Session对象的生命周期与JTA事务绑定

    managed:Hibernate委托程序来管理Session对象的生命周期

  在hibernate.cfg.xml中进行如下配置;

<!--配置session绑定本地线程 -->
thread>

  hibernate提供sessionFactory.getCurrentSession()创建一个session和ThreadLocal绑定方法:

  在HibernateUtil工具类中更改getCurrentSession方法;

//获取当前线程绑定的会话public static Session getCurrentSession(){    return sessionFactory.getCurrentSession();   }

  而且Hibernate中提供的这个与线程绑定的session可以不用关闭,当线程执行结束后,就会自动关闭了。

转载地址:http://vyuuz.baihongyu.com/

你可能感兴趣的文章
No compiler is provided in this environment. Perhaps you are running on a JRE rather than a JDK?
查看>>
no connection could be made because the target machine actively refused it.问题解决
查看>>
No Datastore Session bound to thread, and configuration does not allow creation of non-transactional
查看>>
No fallbackFactory instance of type class com.ruoyi---SpringCloud Alibaba_若依微服务框架改造---工作笔记005
查看>>
No Feign Client for loadBalancing defined. Did you forget to include spring-cloud-starter-loadbalanc
查看>>
No mapping found for HTTP request with URI [/...] in DispatcherServlet with name ...的解决方法
查看>>
No mapping found for HTTP request with URI [/logout.do] in DispatcherServlet with name 'springmvc'
查看>>
No module named 'crispy_forms'等使用pycharm开发
查看>>
No module named cv2
查看>>
No module named tensorboard.main在安装tensorboardX的时候遇到的问题
查看>>
No module named ‘MySQLdb‘错误解决No module named ‘MySQLdb‘错误解决
查看>>
No new migrations found. Your system is up-to-date.
查看>>
No qualifying bean of type XXX found for dependency XXX.
查看>>
No qualifying bean of type ‘com.netflix.discovery.AbstractDiscoveryClientOptionalArgs<?>‘ available
查看>>
No resource identifier found for attribute 'srcCompat' in package的解决办法
查看>>
no session found for current thread
查看>>
No static resource favicon.ico.
查看>>
no such file or directory AndroidManifest.xml
查看>>
No toolchains found in the NDK toolchains folder for ABI with prefix: mips64el-linux-android
查看>>
NO.23 ZenTaoPHP目录结构
查看>>