1

Last week, we passed this article "Why caught an exception, but the transaction still rolled back?" " to explain the reasons why the previous test4 will roll back.

However, I still received a lot of unintelligible feedback. It was mainly based on the clues given in the previous article to track. It was a rollback indication and exception. What everyone did not understand was that the javax.validation.ConstraintViolationException exception was not finally thrown out. So why is the catch in test4 not able to catch it?

In fact, this problem is not difficult to explain. Let's do a small experiment through this article to help you further understand this question!

If you still don’t understand what this article is discussing, I suggest you read the previous two articles first:

Try it out

Since @Transactional is realized through aspects, it may not be easy to understand the whole process through the source code.

So, here is a simple way to understand why the catch of test4 did not catch the exception.

We add more log information and breakpoints to test4 in a way similar to the following:

At the same time, remember to also add a breakpoint to the transaction commit entry mentioned in the previous article.

org.springframework.orm.jpa.JpaTransactionManager

Then try to trigger the execution of test4. Through DEBUG, we can all observe:

In test4, the breakpoints we added, except for line 47 were not entered, the rest were executed all at once. Before entering the org.springframework.orm.jpa.JpaTransactionManager of doCommit method.

Therefore, the exceptions thrown by the transaction rollback we tracked in the previous article are actually thrown after the try-catch block in test4 is executed, so the internal catch cannot catch the exception, here is the catch. Lonely.

Through the log, we can also observe this execution sequence:

Well, looking at it this way, is it better to understand it than before? If you want to further understand the underlying operating mechanism of the transaction, you must debug the source code, go through it yourself, and you will have a deep understanding! If you have any other questions, welcome to join our Spring technical exchange group , participate in exchanges and discussions, learn and progress together! If you are learning Spring Boot, my free tutorials have been serialized continuously, welcome to follow Spring Boot 2.x basic tutorial .

Welcome to pay attention to my public account: Program Ape DD, share knowledge and thoughts that can’t be seen elsewhere

程序猿DD
2.2k 声望2.8k 粉丝

作品:《Spring Cloud微服务实战》、SpringForAll社区、OpenWrite、Youtube中文配音