Sobes.tech
Senior

How to create a transaction manually without the @Transactional annotation?

sobes.tech AI

Answer from AI

To create a transaction manually without using the @Transactional annotation in Spring, you can use PlatformTransactionManager and TransactionTemplate or work directly with TransactionStatus.

Example using PlatformTransactionManager:

@Autowired
private PlatformTransactionManager transactionManager;

public void manualTransaction() {
    DefaultTransactionDefinition def = new DefaultTransactionDefinition();
    def.setIsolationLevel(TransactionDefinition.ISOLATION_DEFAULT);
    def.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRED);

    TransactionStatus status = transactionManager.getTransaction(def);
    try {
        // Your database operations

        transactionManager.commit(status); // commit the transaction
    } catch (Exception ex) {
        transactionManager.rollback(status); // rollback the transaction on error
        throw ex;
    }
}

Thus, you manually control the beginning, commit, and rollback of the transaction without using annotations.