Sobes.tech
Middle

Where have you used the @Transactional annotation?

sobes.tech AI

Answer from AI

In the application's service layers, methods requiring transactional management are designated. This ensures the atomicity of database operations.

Examples:

  • Methods performing multiple write operations (INSERT, UPDATE, DELETE) that must either succeed completely or be rolled back in case of an error.
  • Methods accessing multiple tables, whose integrity must be maintained.
  • Methods fetching data where read consistency is important (using different isolation levels).

Often used in conjunction with Spring Data JPA repositories.

Configured annotation parameters:

  • propagation: Defines how transactions propagate between methods. For example, REQUIRED (uses the current or creates a new one), REQUIRES_NEW (always creates a new one).
  • isolation: The transaction isolation level. For example, READ_COMMITTED, REPEATABLE_READ.
  • readOnly: Indicates that the transaction is read-only, optimizing performance.
  • rollbackFor / noRollbackFor: Specifies exception types for which the transaction should (or should not) be rolled back.

Code example:

import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Service
public class OrderService {

    // In a real example, there would be a repository or another dependent service here

    @Transactional
    public void placeOrder(Order order) {
        // Order placement logic
        // Saving order to DB
        // Deducting funds
        // Sending notification
    }

    @Transactional(readOnly = true, isolation = Isolation.READ_COMMITTED)
    public Order getOrderById(Long orderId) {
        // Logic to retrieve order
        return null; // placeholder
    }

    @Transactional(rollbackFor = Exception.class)
    public void processPayment(Payment payment) throws Exception {
        // Payment processing logic
        // Throw exception if something goes wrong
        // throw new Exception("Payment processing failed");
    }
}

Using @Transactional helps separate transaction management logic from the main business logic, making the code cleaner and more maintainable.

Where have you used the @Transactional annotation… - sobes.tech