Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to understand Spring two-tier transaction

2025-03-28 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/03 Report--

This article mainly explains "how to understand Spring double-tier transactions". The content of the article is simple and clear, and it is easy to learn and understand. Please follow the editor's train of thought to study and learn "how to understand Spring double-tier transactions".

System A calls system B to perform data synchronization, and system B returns an error prompt. System A needs to roll back the previously saved data and throw the error message up.

The approximate code is as follows

@ Service ("noteService") public class NoteServiceImpl implements NoteService {@ Resource private SearchService searchService; @ Transactional (rollbackFor = Throwable.class) @ Override public CommonResponse save (NoteEntity note) {/ / a series of DB operations try {searchService.sync (note);} catch (Exception e) {e.printStackTrace () } return CommonResponse.success (entity);} @ Service ("searchService") public class SearchServiceImpl implements SearchService {@ Transactional (rollbackFor = Throwable.class) @ Override public void sync (NoteEntity note) {/ / a series of DB operations throw new RuntimeException ("synchronization exception! [XXX] ");} @ SpringBootTest public class NoteTests {@ Resource private NoteService noteService; @ Test public void saveNote () {NoteEntity entity = new NoteEntity (); entity.setTitle (" Nian Nujiao Chibi nostalgia "); entity.setContent (" the river goes east, the waves are swept away, the romantic figures are immortal. " Therefore, to the west of the base, humanity is: the three Kingdoms Zhou Lang Chibi. ") ; entity.setTags (Su Shi, Song Dynasty); entity.setCategory (Su Shi's Poems); try {noteService.save (entity);} catch (Exception e) {e.printStackTrace (); / / FIXME I want to get synchronization anomalies here! [XXX] / / FIXME but what you get here is Transaction silently rolled back because it has been marked as rollback-only System.out.println (">" + e.getMessage ());}

Where there is smoke, there is fire

The code has a long history, and why it is written in this way can no longer be traced.

After wondering for a while, when I saw the two-tier transaction, I thought of the Spring transaction propagation mechanism, which was understood more shallowly. I have sorted out all the Spring series interview questions and answers, please follow the official account Java technology stack, reply: interview.

Without special configuration, we naturally follow the default transaction propagation mechanism, that is, Propagation.REQUIRED.

International practice, listing transaction communication mechanisms:

1. PROPAGATION_REQUIRED currently has no transaction, then create a transaction; if there is a transaction, join the transaction, which is the most commonly used setting. 2. If there is a transaction in PROPAGATION_SUPPORTS, join the transaction, and if there is no transaction, it will be executed in a non-transactional manner. 3. If there is a transaction in PROPAGATION_MANDATORY, join the transaction; if there is no transaction, an exception is thrown. 4. PROPAGATION_REQUIRES_NEW creates a new transaction unconditionally. 5. PROPAGATION_NOT_SUPPORTED is executed in a non-transactional manner, suspending the current transaction if there is a current transaction. 6. PROPAGATION_NEVER runs in a non-transactional manner. If there is a transaction, an exception is thrown. 7. Before PROPAGATION_NESTED starts to execute a transaction, save a savepoint. When an exception occurs, roll back to the savepoint; when there is no exception, commit or roll back along with the external transaction.

Specific reasons

1. After looking at the transaction propagation mechanism above, we continue to refine the problem. The inner and outer layers share a transaction, and the inner layer throws an exception, which will cause the whole transaction to fail.

2. Continue the analysis. If the outer layer logic try catch, the inner layer exception cannot be thrown upward, and the outer layer transaction will continue to commit.

3. When the transaction commits, the transaction status is judged, and it is found that the transaction is failed and needs to be rolled back, so an exception of Transaction silently rolled back because it has been marked as rollback-only is thrown.

How to solve it?

Naturally, there is no silver bullet, so choose the right solution according to the business scenario.

1. In the current scenario, you can simply remove the try catch from the outer logic. If the exception is thrown directly up, the transaction will not continue to commit, and the caller will get the first-hand exception.

2. If the inner layer is not the core logic and record a log or something, you can configure the inner transaction to @ Transactional (rollbackFor = Throwable.class, propagation = Propagation.REQUIRES_NEW). In any case, a new transaction is created, and the outer transaction is not affected by the inner transaction. However, there is a problem. The outer transaction fails, but the inner transaction still stores the records, which may produce dirty data.

3. If the outer transaction fails and the inner transaction cannot be committed, you can use @ Transactional (rollbackFor = Throwable.class, propagation = Propagation.NESTED). Note: hibernate/jpa does not support nested transaction NESTED, it can be replaced by JdbcTemplate.

Thank you for your reading, the above is the content of "how to understand Spring double-tier transactions". After the study of this article, I believe you have a deeper understanding of how to understand Spring two-tier transactions, and the specific use needs to be verified in practice. Here is, the editor will push for you more related knowledge points of the article, welcome to follow!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report