The annotation @Transactional in Spring Boot
Introduce
The @Transactional annotation is part of the Spring Framework and is used to manage transactions declaratively. It can be applied to classes or methods in your service layer.
@Transactional under the hook.
The image depicts that the transactional bound context will applied to all methods in this class. When we call the method annotated by @Transactional by default it will be wrapped within an TransactionAspectSupport class and the actual method is executed in invokeWithinTransaction method (We can use this to check if we are configure transaction in our application correctly).
Recommended by LinkedIn
Key to takeaways
Luckily, the spring framework does the job for us to make SimpleJpaRepository (which is the parent class of JpaRepository we usually use) annotated with read-only transactions.
With this setup, the @Transactional we write is useless since we can't find any TransactionAspectSupport in the call stack.
⚡ AI Engineer | FE Developer | ReactJS | Database Optimization
9moVery helpful!
⚡️Software Developer
9moThanks for sharing
⚡ Culi developer Chia sẻ về những điều mình biết, những sai lầm đã gặp phải và giải pháp luôn :D Whatever you are not changing, you are choosing Let's connect!
9mogreat post. It make me remember 1 question I got when do interview: Have you ever faced the problem when your @transaction called another service with @transaction? What happens if the inner transaction falls back? At first, he used the term transaction propagation and I have no idea what's it
Senior Software Architect @ VPS Securities JSC
9moCảm ơn bạn, bài viết rất hay và dễ hiểu. Đầy đủ các trường hợp và lưu ý khi sử dụng. Việc sử dụng @Transactional thì AOP sẽ tạo ra proxy class, bản thân method trong class gọi nhau sẽ k đi qua lớp proxy này. Các annotation khác cũng như thế. Nói chung bài viết rất thực tế và áp dụng được ngay và luôn.