Instead of naive implementation of findOrSave
operation ...
public Foo findOrSaveFoo(Foo foo) {
return fooRepository
.findFoo(foo)
.orElseGet(() -> saveFoo(foo));
}
... which has check-than-act concurrency problem, I need something like this:
public Foo findOrSaveFoo(Foo foo) {
try {
return saveFoo(foo);
} catch (DataIntegrityViolationException ignore) {
return fooRepository
.findFoo(foo)
.orElseThrow(AssertionError::new);
}
}
But it causes problems with Session
at .findFoo(foo)
line:
null id in ... entry (don't flush the Session after an exception occurs)
org.hibernate.AssertionFailure: null id in ... entry (don't flush the Session after an exception occurs)
Is there a way to avoid this exception or any alternative thread-safe implementation for findOrSaveFoo
?