通过 spring 注释进行事务 - 只读或非只读?
我的项目代码类似于此
@Transactional(readOnly = true)
public void tt() {
dd();
}
@Transactional()
public void dd() {
gg();
}
@Transactional(readOnly = true)
public void gg() {
}
函数 dd 既被其他只读事务函数使用,也被只读函数使用。假设事务应该从 tt 的执行扩展到 gg - dd 中的操作是否是只读事务?
I've got in my project code similar to this
@Transactional(readOnly = true)
public void tt() {
dd();
}
@Transactional()
public void dd() {
gg();
}
@Transactional(readOnly = true)
public void gg() {
}
Function dd is used both by other readonly transaction functions and not readonly functions. Assuming that transaction should extendend from execution of tt to gg - operations in dd will in be read-only transaction or not?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
在这个特定的例子中,你的问题没有实际意义。
从
tt()
调用dd()
不会通过代理边界,因此不会向dd()
应用事务建议(因为这是同一实例内的调用)。与从dd()
调用gg()
相同。因此,只有从外部对tt()
的调用实际上才是交易建议的(在您的情况下,使用readOnly=true
),并且这将是交易在整个调用链中使用。但在一般情况下,请阅读 @melihcelik 暗示的文档 - 它解释了该行为。
In this particular example, your question is moot.
The call to
dd()
fromtt()
will not pass the proxy boundary so no transactional advise will be applied todd()
(since it's a call inside the same instance). Same with the call togg()
fromdd()
. Consequently, only the call from outside tott()
would actually be transaction-advised (in your case, withreadOnly=true
) and that would be the transaction that would be used in the entire call-chain.In the general case though, read the documentation hinted by @melihcelik - it explains the behavior.
Spring 的
AbstractPlatformTransactionManager
有一个名为validateExistingTransaction
的属性来控制此行为。 Javadoc 指出:由于 Spring
@Transactional
注释的默认传播是REQUIRED
并且默认验证策略为 false,我希望 Spring 使用从tt
方法调用创建的现有事务处于只读模式。如果你想要一个只读事务,那么你必须用以下方式注释你的方法:
Spring's
AbstractPlatformTransactionManager
has a property namedvalidateExistingTransaction
that controls this behavior. Javadoc states that:Since default propagation for Spring
@Transactional
annotation isREQUIRED
and default validation strategy is false, I expect Spring to use existing transaction created fromtt
method call in readonly mode.If you want to have a read only transaction, then you have to annotate your method with:
如果您正在执行 get/select 并且不进行任何更改,请使用@Transactional(readoOnly = true) ,这意味着不会应用任何锁(这更有效)。
对于更新/插入/删除/保存/合并,我使用(当需要锁时):
use
@Transactional(readoOnly = true)
if you are performing a get/select and not making any changes, this means that no locks will be applied (which is more efficent).For updates/inserts/deletions/saves/merges I use (when a lock is required) :