API / Apache Grails Interview questions
Why should you mark long-running database work with @Transactional at the service layer?
Grails services get transactional behavior automatically by convention, but understanding why that matters — and when to be explicit about it with @Transactional — comes down to guaranteeing that a group of related database operations either all succeed together or all roll back together.
Consider transferring funds between two accounts: debiting one and crediting the other are two separate GORM operations, but they represent a single logical unit of work. Without a transaction boundary around both, a failure between the debit and the credit (a network blip, an unexpected exception) could leave the database in an inconsistent state — money debited from one account but never credited to the other. Wrapping both calls inside a transactional service method guarantees that if anything fails partway through, every change made so far in that method rolls back, leaving the database exactly as it was before the operation started.
While a service's public methods are transactional by default, being explicit with @Transactional (and its propagation/isolation settings when relevant) still matters for clarity, for controlling behavior on private/protected helper methods that don't get the automatic wrapping, and for fine-tuning things like read-only transactions for pure query methods where the default write-transaction overhead isn't needed.
More Related questions...