I have two entities with one-to-one association. And some services that works with them in parallel. I need to delete one, but sometimes i have DataIntegrityViolationException, that as i understand means that i can't delete some entity while other has foreign key on it.
Here is my entities:
public class Foo{
@Id
@GeneratedValue
private Long id;
}
and:
public class Bar{
@Id
@GeneratedValue
private Long id;
@ManyToOne
private Foo foo;
}
Method that doesn't work (all repos extends from JpaRepository):
@Transactional
public void deleteFoo(Long fooId) {
barRepository.deleteAllByFooId(fooId);
fooRepository.deleteById(fooId);
}
And some method that works in parallel and breaks everything:
@Transactional
public void method(Long fooId) {
...
Foo foo = fooRepository.findById(fooId);
barRepository.save(new Bar(foo));
...
}
So i have ConstraintViolationException, as i understand because im trying to delete Foo but i have that new Bar(foo)
in method
that wasn't deleted by barRepository.deleteAllByFooId(fooId)
in deleteFoo
.
I need some approach like "delete method should wait until all current transactions finishes and then run only one transaction".
Can't use KeyLockManager
because real structure of project already enough complicated and if i use it it should be same lock in many classes.