'Concurrent bulk saving - duplicate item in mysql with JPA

I am using JPA's saveAll method for bulk save of a list of employees into mysql database in a microservice architecture.

However, there could be duplicates and concurrent requests( anywhere between 2 to 7 requests at the same time). How can I handle duplicates in such a scenario ?

Two possible solutions i can think of:-

  1. fetch records and eliminate duplicate employees from the list before calling saveAll. Problem: concurrent requests could result in race condition and exceptions

  2. catch the exception and retry the operation Problem: recursive approach is not considered a best practice as it could lead to large number of iterations ?

What can i do in such a situation ?



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source