@transactional decorator automatically wraps methods in transactions, reducing boilerplate code.
Decorator Overview
Automatic Transactions
Automatically wraps method execution in transaction Commits on success, rollbacks on failure
Cleaner Code
No need to call transaction() Improved readability
Isolation Level
Configure transaction isolation level Concurrency control
Nested Transactions
Automatic context sharing Savepoint support
Basic Usage
Before: Manual Transactions
After: @transactional Decorator
Methods decorated with
@transactional() automatically run within a transaction.How It Works
Decorator Options
dbPreset Setting
Isolation Level Setting
Practical Examples
Example 1: Simple Transaction
Example 2: Automatic Rollback
Example 3: Complex Transaction (Company → Dept → Employee)
Example 4: Concurrency Control
Nested Transactions
Automatic Context Sharing
Benefits of Nested Transactions: - Improved code reusability - Freedom to combine methods -
Automatic transaction boundary management
Using with @api
Combining Decorators
Pros and Cons
Pros
Cleaner Code
No need for transaction() calls Removes boilerplate
Readability
Clear transaction boundaries Focus on business logic
Auto Management
Auto commit/rollback handling Prevents mistakes
Reusability
Easy method composition Nested transaction support
Cons
Constraints
Only usable at method level Partial transactions not possible
Debugging
Transaction boundaries are hidden May be harder to trace issues
Usage Guidelines
When to Use?
✅ Recommended:- Entire method is one transaction
- Multiple DB operations require atomicity
- Code reuse is important
- API handler methods
- Partial transactions within method
- Complex transaction control needed
- Transaction boundaries need to be explicit
Pattern Comparison
Important Notes
Common Mistakes
Next Steps
Manual Transactions
Using transaction() directly
Best Practices
Transaction usage guide
UpsertBuilder
Saving data in transactions
Decorators
Understanding Sonamu decorators