Chathura Buddhika
Chathura Buddhika

Reputation: 2195

Spring boot @Transactioanl method running on multiple threads

In my spring boot application, I have parallel running multiple threads of following @Transactioanl method.

@Transactional
public void run(Customer customer) {

    Customer customer = this.clientCustomerService.findByCustomerName(customer.getname());
    if(customer == null) {
        this.clientCustomerService.save(customer);
    }

    // another database oparations
}

When this running on multiple threads at the same time, since customer object will not be save until end of the transaction block, is there any possibility to duplicate customers in the database?

Upvotes: 1

Views: 231

Answers (1)

Dina Bogdan
Dina Bogdan

Reputation: 4698

If your customer has an @Idfield which define a Primary Key column in Customer database, the database will throw you an exception like javax.persistence.EntityExistsException. Even if you run your code on multiple threads, at a point in time, maybe at the database level, only one will acquire a lock on the new inserted row. Also you must define @Version column/field at top entity level in order to use optimistic-locking. More details about this you can find here.

Upvotes: 1

Related Questions