withTransaction和grails中的withSession有什么区别? [英] What is the difference between withTransaction and withSession in grails?

查看:279
本文介绍了withTransaction和grails中的withSession有什么区别?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道一个人获得底层会议,另一个人获得当前交易状态的参考;然而,他们之间的区别是什么以及每个用例是什么样的?我的要求是在Service方法块中批量保存一些记录。 / p>

解决方案

withTransaction 有点琐碎,因为它允许你做事务性工作任何地方都可以,但最好将问题分开,并在交易服务中完成工作。除非添加 static transactional = false ,并且可以在类和/或方法级别使用 @Transactional进行微调,否则默认情况下服务是事务性的注释。你应该没问题,只要把你的代码放在服务方法中,而不用 withTransaction withSession



withSession 是访问当前Hibernate Session (通常是一个由OpenSessionInView拦截器注册)。如果您想清除会话或执行其他未由GORM公开的工作,则可以在不访问 sessionFactory 或线程本地持有者的情况下访问它,在事务服务方法之外, withTransaction 的一个有效使用是绑定一个Hibernate Session ,当你在控制器请求之外(即没有自动创建的 Session )时。 withTransaction 将启动一个事务并根据需要创建一个 Session ,并在关闭期间保持打开状态。所以你可以使用它来避免延迟加载异常。我们需要另一种方式来完成这个任务,而不需要事务的开销,对于那些刚刚从数据库读取并且不需要事务性写入的情况。但现在,这种方法很有效。但是,如果您执行数据库写入操作,请将代码移至服务方法。


I know one gets the underlying session and the other a reference to the current transaction status; however, what are the differences between them and what would be an example use-case for each?

My requirement is to batch save some records within a Service method block.

解决方案

withTransaction is a bit hackish because it allows you to do transactional work anywhere, but it's best to separate your concerns and do the work in a transactional service. A service is transactional by default unless you add static transactional = false and can be fine-tuned at the class and/or method level with the @Transactional annotation. You should be fine just putting your code in a service method without using withTransaction or withSession.

withSession is a convenient way to access the current Hibernate Session (typically the one registered by the OpenSessionInView interceptor). If you want to clear the session, or do other work that's not exposed by GORM, this is a way to access it without accessing the sessionFactory or the thread-local holders that Spring uses.

One somewhat valid use of withTransaction outside of a transactional service method is to bind a Hibernate Session when you're outside of a controller request (i.e. when there's no auto-created Session). withTransaction will start a transaction and create a Session if needed, and keep it open for the duration of the closure. So you can use it to avoid lazy-loading exceptions. We need another way to do this without the overhead of a transaction, for those cases when you're just reading from the database and don't need transactional writes. But for now, this approach works. However if you do database writes, move the code to a service method.

这篇关于withTransaction和grails中的withSession有什么区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆