Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 696
Robin Jonsson Avatar asked Jul 21 '17 09:07

Robin Jonsson


People also ask

Can I use multiple transaction managers within a Spring application?

You just need to create two transaction managers and inject them with the appropriate connection.

Can we have multiple repository in Spring boot?

You can only have one repository per entity... however, you can have multiple entities per table; thus, having multiple repositories per table.

What is difference between JpaRepository and PagingAndSortingRepository?

PagingAndSortingRepository provides methods to do pagination and sort records. JpaRepository provides JPA related methods such as flushing the persistence context and delete records in a batch.

Does @transactional lock table Spring?

"@Transactional" as itself on any isolation level doesn't enabling any locking. To achieve locking behaviour you should use "@Lock" annotation or use " for update" in your query.


1 Answers

It is usually a wrong idea to have @Transactional declared around repository methods.

Repositories are only for you to access domain entities. Business logic normally involves multiple domain entities and collaborations between them.

In your architecture you should have a layer to compose business logic. This usually corresponds to a service exposed to external.

This is usually the place you should have your transaction boundary set on. Usually it is a Controller, or a Service method.

like image 166
Adrian Shum Avatar answered Sep 18 '22 12:09

Adrian Shum