Safari
Safari

Reputation: 11945

Spring JPA atomic get or create method

I'm using Spring Boot and JPA (with Hibernate).

I have a method (into my service) to:

Obviously, I need to guarantee the atomicity for this method.

I must to avoid separate transactions that risk creating duplicate entries in the DB.

An additional note: on the Users table I cant to add some unique constraints because there are some different combinations for this (for example, I can create again the same user if the status is in a certain value or something like this).

I tried to use only the @Transactional annotation for my method but I noticed this is not enough (using some stress test I'm able to create multiple rows into the DB).

So now I'm confused.

What's the best practice to have an atomic method? Have I to change the Transaction Isolation level? Have I to use some Locks?

I'm not a Spring expert but I think that this is a common problem but I'm not able to understand what is the correct way.

Basically I'm looking for an atomic GET_OR_CREATE method using the JPA (and JPA repository)

Upvotes: 3

Views: 4037

Answers (1)

Simon Martinelli
Simon Martinelli

Reputation: 36203

In that case you will need to set the Transaction isolation level to SERIALIZABLE that only one transaction can access the database. This can be done using the isolation attribute of the Transactional annotation:

@Transactional(isolation = Isolation.SERIALIZABLE)
public void yourMethod(){
    // ...
}

Read more about that topic here: https://www.baeldung.com/spring-transactional-propagation-isolation

Upvotes: 2

Related Questions