Java Transactions
In Java, transactions are a way to manage a group of operations as a single unit of work, ensuring that either all the operations within the group are executed successfully, or none of them are executed at all. Transactions are commonly used when dealing with databases or any other systems that require data consistency and integrity.
The key concepts in transactions are known under abbreviation ACID:
1. Atomicity ensures that all the operations within a transaction are treated as a single indivisible unit. If any part of the transaction fails, the whole transaction is rolled back, and the data is left unchanged.
2. Consistency guarantees that a transaction brings the database from one valid state to another. It enforces integrity constraints, ensuring that data remains in a valid and consistent state after the transaction completes successfully.
3. Isolation is taking care of that each transaction is isolated from other concurrent transactions. Transactions should not interfere with each other, and each one should feel like it's running in isolation.
4. Durability ensures that once a transaction is committed, the changes made to the data persist even in the face of system failures, such as power outages or crashes.
Lets look at some examples in Spring Boot application.
First we need to enable transaction manager in a configuration component and register PlatformTransactionManager in the application context like bellow:
Transaction manager configuration
Then we can start using @Transactional annotation on our classes and methods. This annotation applied on a method will ensure that all the steps in that method complete or none of them. If the transaction fails at any step it will rollback all the operations it did before.
@Transactional example
In the example above, neither of two users will be persisted to the database because at the end we are throwing CustomException, whick extends Exception class. In @Transactional annotation we can specify e.g. on which exceptions we want to rollback all operations.
Important thing to note is that transactions are not limited to just database operations. You can use similar concepts and frameworks for managing transactions involving other resources like files, message queues, etc. The key is to ensure that related operations are treated as a single unit with the ACID properties in mind.