Hibernate and Spring ensure data integrity during concurrent operations. It is crucial to understand two key mechanisms here: transactions, which define the boundaries of a unit of work, and locks, which resolve conflicts during concurrent access.
Transaction Management in Spring and Hibernate
At the core is the @Transactional annotation, which wraps a method in a transaction via Spring AOP (proxies) and decides when to commit or roll it back.
Key point — Rollback Rules:
By default, Spring rolls back a transaction only for unchecked exceptions ( RuntimeException and Error ). For checked exceptions (subclasses of Exception , but not RuntimeException ), the transaction commits by default. This is a frequent source of errors: a developer throws an IOException and expects a rollback, but the data is partially saved.
// Explicit rollback management @Transactional ( // rollback for checked exceptions rollbackFor = { IOException . class , PaymentGatewayException .…