Spring
Top 10 Questions of @Transactional annotation in Spring
Questions and answers on transaction boundaries, propagation, and rollback with Spring's Transactional annotation.
-
What does
@Transactionaldo in Spring?
It manages transactions automatically, ensuring data consistency by committing or rolling back operations. -
Where can
@Transactionalbe applied?
It can be applied to methods or classes, typically in service-layer components. -
What is the default propagation behavior of
@Transactional?
The default propagation isREQUIRED, creating a new transaction or joining an existing one. -
How does
@Transactionalhandle rollbacks?
It rolls back on unchecked exceptions (e.g.,RuntimeException) by default, unless specified otherwise. -
Can
@Transactionalbe used with private methods?
No, it works only on public methods due to Spring's proxy-based mechanism. -
What is the
readOnlyattribute in@Transactional?
readOnly=trueoptimizes for read-only operations, preventing unnecessary transaction overhead. -
How does the
isolationattribute work in@Transactional?
It defines transaction isolation levels, likeDEFAULT, to control data visibility during transactions. -
What happens if
@Transactionalis used without a transaction manager?
Spring throws an exception if no transaction manager is configured for the application context. -
Can
@Transactionalbe nested?
Yes, but nested behavior depends on thepropagationsetting, likeNESTEDorREQUIRED. -
How does
@Transactionalinteract with Spring Boot?
Spring Boot auto-configures a transaction manager, enabling seamless use of@Transactional.