Why We Use @Transactional in Our Project #153
poksyy
started this conversation in
Show and tell
Replies: 0 comments
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Uh oh!
There was an error while loading. Please reload this page.
-
What is @transactional?
@transactional is a Spring annotation used to define a method or class as part of a transaction. This ensures that multiple database operations are executed atomically—either all succeed or none are applied, maintaining the integrity of the data.
Why Implement @transactional?
In our project, we use @transactional to ensure database consistency during operations like user registration, password reset, and updates. Without it, partial updates could be made to the database if an error occurs mid-process. Using @transactional ensures that if an operation fails, all changes are rolled back, keeping the database in a consistent state.
Example: User Password Reset
Without @transactional:
In the above method, if an error occurs (e.g., userRepository.save() fails), the changes made to the user’s password would still persist, potentially causing inconsistency.
With @transactional:
In this version, if an exception is thrown during any step, the transaction is rolled back, and no changes are made to the database, preserving consistency.
Conclusion
By using @transactional, we ensure that all database changes within a method are executed atomically. If any error occurs, the transaction is rolled back, keeping the database in a consistent state and avoiding partial updates.
Beta Was this translation helpful? Give feedback.
All reactions