'EntityManager persist not updating entities

So I have a scenario where I have to either create new entities, or update already existing ones and I'm doing all that and in the end using the entitymanager persist in batches, then flushing and clearing, for optimization, because the JPA repository is too heavy and slow for this amount of data. However I'm getting a problem that is a ConstraintViolationException for a unique key. I have a composite unique key which is made from an ID and name and for some reason when I try to do a persist I sometimes get the exception where the unique constraint is violated, meaning it tries to insert two duplicate entities. I logged all the entities and saw that there are no duplicates so I'm curious what the case could be. I've considered using merge() instead of persist but I am not sure if that can fix the issue, for example splitting the list in two parts - to be created and inserted and to be updated, and using persist for new entities and merge for existing ones. Could any of those help me or perhaps a better suggestion?



Sources

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

Source: Stack Overflow

Solution Source