[英]How to make transaction only effect in a method when a annotated Transactional is added in both class and method?
I had an interview, and during the interview, I was asked the following question: When the @Transactional
annotation is added to both the class and one method, but not on other methods, how can I only make the transaction of this method effective? 我进行了一次采访,在采访中,我被问到以下问题:当
@Transactional
批注同时添加到类和一个方法时,而不是在其他方法上时,如何使该方法的事务有效?
For example: 例如:
@Transactional
public class ClassA {
@Transactional
private void methodA() {
}
private void methodB() {
}
private void methodC() {
}
}
So, how can I make sure that the other transactions within the class do not take effect? 因此,如何确保该类中的其他事务不生效? What does this question focus on?
这个问题的重点是什么?
You can change the propagation type of the inner transaction: 您可以更改内部事务的传播类型:
@Transactional(propagation = Propagation.REQUIRES_NEW)
This will create a new inner transaction and suspend the outer transaction. 这将创建一个新的内部事务并暂停外部事务。 This might be useful if you need an inner transaction to commit, but you need the outer transaction to still rollback if there are any issues elsewhere.
如果您需要提交内部事务,但是如果其他地方有任何问题,则需要外部事务回滚,这可能会很有用。
I have never used a class-scoped @Transactional
, but the propagation
property is actually pretty useful to know about. 我从未使用过类作用域的
@Transactional
,但是知道propagation
属性实际上非常有用。
I have used it in several cases to override the default, Propagation.REQUIRED
, which says: 'create a new transaction if one does not already exist - otherwise support the current transaction', according to the docs. 我在几种情况下都使用它来覆盖默认值
Propagation.REQUIRED
,该默认值说:“如果尚不存在,则创建一个新事务-否则支持当前事务”,根据文档。
By the way, I am using: 顺便说一句,我正在使用:
org.springframework.transaction.annotation.Transactional
So my answer does not apply if you are using an alternative @Transactional
因此,如果您使用其他
@Transactional
则我的答案不适用
Also note that the inner and outer transaction distinction is HQL-based, so you don't need to worry about the SQL dialect you're using. 还要注意,内部事务和外部事务的区别是基于HQL的,因此您不必担心所使用的SQL方言。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.