Setup: SpringBoot application using SpringJPA with Hibernate
I have two entities: A and B. Set is a child of A.
I want to remove a B and create another one in a characteristic which would hit a unique constraint. To avoid that I first need to delete the old B before creating a new one. Since I am in a transaction, I have to flush after deletion.
Executing the following code will still fail:
@Transactional
void removeOldBsAndCreateNewOnes(A a) {
final Set<B> bSet = a.getBs();
final Set<B> removedBs = new HashSet<>();
bSet.stream()
.filter(
//magic stuff here
)
.forEach(b -> {
bRepository.delete(b);
// Flush is needed as we are in a transaction and not flushing will make hibernate to insert the new B first on commit which will violate the configured unique constraints.
bRepository.flush();
removedBs.add(b);
});
bSet.removeAll(removedBs);
final Set<B> newBs = new HashSet<>();
// Doing some stuff to detemine new Bs
bRepository.saveAll(newBs);
bSet.addAll(newBs);
}
Nevertheless I get a unique constraint violation error. flush() is not executed.
I already searched for reasons and looked here without success: