Search code examples
javaspringhibernatespring-data

Spring Data Transaction spanning multiple Repositories


I have the need to insert 2 different entities into 2 different tables, using the same transaction. If the second insert fails, the first one should be rolled back.

Is there any way of doing this nicely?

Pseudo code:

start tx
repo1.save(myEntity);
repo2.save(anotherEntity);
try commit

I know you can leverage @Transactioal but only on method level?


Solution

    1. you need check that you don't have set autocommit = false.

    2. wrap save operations into one service method and make it @Transactional. But if you use save() custom method check that save in not marked as @Transactional with propagation level required_new or nested. If you need you can use REQUIRES_NEW for saving service method to make this service method transaction independent of other transactions.

    also you can wrap in with TransactionTemplate.

    @Autowired
    private TransactionTemplate transactionTemplate;
    
    transactionTemplate.execute(new TransactionCallbackWithoutResult() {
        @Override
        public void doInTransactionWithoutResult(TransactionStatus transactionStatus) {
                repo1.save(myEntity);
                repo2.save(anotherEntity);
        });