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

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

问题描述

我知道一个获取基础会话,另一个获取当前事务状态的引用;但是,它们之间有什么区别,每个用例的示例是什么?

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?

我的需求是在一个 Service 方法块中批量保存一些记录.

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

推荐答案

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

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 是一种访问当前 Hibernate Session(通常是由 OpenSessionInView 拦截器注册的)的便捷方式.如果您想清除会话,或执行 GORM 未公开的其他工作,这是一种无需访问 sessionFactory 或 Spring 使用的线程本地持有者即可访问它的方法.

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.

在事务服务方法之外使用 withTransaction 的一个有效用途是,当您在控制器请求之外时(即,当没有 auto-创建 Session).withTransaction 将启动一个事务并在需要时创建一个 Session,并在关闭期间保持打开状态.所以你可以用它来避免延迟加载异常.我们需要另一种没有事务开销的方法来做到这一点,对于那些你只是从数据库读取而不需要事务写入的情况.但就目前而言,这种方法有效.但是,如果您进行数据库写入,请将代码移至服务方法.

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.

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

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