当前位置:网站首页>@Several scenarios of transactional failure

@Several scenarios of transactional failure

2022-06-28 04:04:00 Cloud on cloud

Spring Of @Transactional Annotations control which scenarios the transaction does not take effect ?

1. The database engine does not support transactions ( only InnoDB Support )

from MySQL 5.5.5 The default storage engine to start with is :InnoDB, Before the default is :MyISAM, So it's worth noting , The underlying engine doesn't support transactions. No matter what happens, it's just a waste of time .

[email protected]Transactional  Annotations can only be applied to public The method of visibility

If it is to be used in non public On the way , Can be opened AspectJ The proxy pattern .

The following is from Spring Official documents :

When using proxies, you should apply the @Transactional annotation only to methods with public visibility. If you do annotate protected, private or package-visible methods with the @Transactional annotation, no error is raised, but the annotated method does not exhibit the configured transactional settings. Consider the use of AspectJ (see below) if you need to annotate non-public methods.

3..try-catch abnormal , The transaction will not take effect

It's also the most common , Eat the abnormal , And then don't throw it out , The transaction will not roll back !

spring The transaction of is started before calling the business method , The business method is executed after execution commit or rollback,

Whether a transaction is executed depends on whether it is thrown runtime abnormal . If you throw runtime exception And there's no... In your business approach catch When you arrive , The transaction rolls back .

This situation can be used @Transactional(rollbackFor = Exception.class) Processing or reprocessing catch Manually execute rollback in

 

4. By default ,Spring Would be right Error perhaps RuntimeException Abnormal transaction rollback ,

Others inherit from java.lang.Exception It's abnormal : Such as IOException、TimeoutException etc. , No rollback .

Solution :Transactional Annotation plus rollbackFor attribute , Appoint java.lang.Exception.class;

5. Method calls in the same class , Lead to @Transactional invalid

scene : In development, it is inevitable to call methods in the same class , For example, there is a class Test, One way of it A,A Call the methods of this class B

( No matter how B Yes, it is public still private modification ), But the way A There is no declaration to annotate the transaction , and B There are methods . Then the external call method A after ,

Method B It doesn't work .

reason : Due to the use Spring AOP The agent caused , Because only when the transaction method is called by code other than the current class , Only by Spring Generated proxy objects to manage .

原网站

版权声明
本文为[Cloud on cloud]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/179/202206280324115050.html