Last mod: 2024.11.03
Transactions in SpringBoot
ACID
ACID – Transactivity guarantee, is a set of properties that guarantee the correct processing of transactions in databases. Its name ACID is an acronym for:
- Atomicity – ensures that each transaction is treated as a unit and that they are indivisible. A transaction must execute in full, or in inches.
- Consistency – ensures that database operations do not compromise data integrity.
- Isolation – the guarantee that each transaction must be independent of the other.
- Durability – guarantees that data will not be lost, e.g. due to failure.
Transaction isolation level
Most relational databases provide the ability to operate in four transaction isolation modes:
Isolation level | Dirty reads | Nonrepeatable reads | Phantoms |
---|---|---|---|
Read uncommitted | exist | exist | exist |
Read committed | do not exist | exist | exist |
Repeatable read | do not exist | do not exist | exist |
Serializable | do not exist | do not exist | do not exist |
We can check the default tranaction isolation level, for example, in the MariaDB database:
SELECT @@tx_isolation;
SpringBoot configuration
The first basic thing is to enable transactions in SpringBoot, we do this with the annotation @EnableTransactionManagement:
import org.springframework.context.annotation.Configuration;
import org.springframework.transaction.annotation.EnableTransactionManagement;
@Configuration
@EnableTransactionManagement
public class AppConfig {
// Bean definitions, etc.
}
We can set the isolation level globally in springBoot with a parameter in application.properties:
spring.datasource.hikari.transaction-isolation=TRANSACTION_READ_COMMITTED
When defining each transaction, we have the option to specify the level of isolation:
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Transactional;
@Service
public class ExampleService {
@Transactional(isolation = Isolation.SERIALIZABLE)
public void myTransactionalMethod() {
// Business logic
}
}
How to rollback transaction
By defining an exception that triggers a rollback:
@Transactional(rollbackFor=Exception.class)
or programatically:
TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
Additional SpringBoot parametres
There are also two additional important paramaters:
spring.transaction.default-timeout= # Default transaction timeout in seconds.
spring.transaction.rollback-on-commit-failure= # (true/false) Perform the rollback on commit failures.
The first parameter needs no further description. The second spring.transaction.rollback-on-commit-failure, on the other hand, deserves a more detailed description. If set to true this will automatically rollback transactions for unchecked exceptions RuntimeException and Error.