Spring Data Transaction spanning multiple Repositories

Robin Jonsson :

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?

xyz :

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

2) wrap save operations into one service method and make it @Transactioal. But if you use save() custom method check that save in not marked as @Transactioal 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);
    });

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=475444&siteId=1