Vote count:
0
I want to do a couple of db-operations in a single transaction. It should be rolled back on all failures but one: in the middel of all the db-ops there will be an insert statement which inserts a generated number into a field that has an unique constraint. If this insert fails because the generated number is already present, in should be repeated with a newly generated number until it succeeds. But this insert should not affect the other operations.
Since there are no nested tx in JPA, i am not sure what the best practice would be here. i am wondering if this is such an uncommon case.
I tried it with an "embedded" tx, which is opened with requires-new that suspends the surrounding tx and resumes it after successfully inserting the random number. That worked partially: if there is an exception in the surrounding tx, everything is rolled back but the random number insert.
If i use one single tx, I don't know how i should determine why this tx failed to commit. so i don't know if i have to repeat all the operations with a new random number or leave it because of another failure.
I also tried to explicitely flush the entity manager session after the insert to force the exception before i continue with the rest of the work in hope i could just delete that entity from the EM programmatically and try again. But I didn't find a way to remove that entity from the EM after a failed insert?
I am also using Spring and SpringDataJPA.
@Transactional
public void doSomeThing() {
SomeEntity fooEntity = new SomeEntity()
someEntityRepository.save(fooEntity);
someMoreDbOPs();
RandomNoEntity rndEnt = new RandomNoEntity();
while (true) {
try {
rndEnt.setRandomNumber(generateRandomNumber());
entityManager.persist(rndEnt);
entityManager.flush();
break;
} catch (ConstraintViolationException)
{
//entityManager.detach(rndEnt); // didnt work
//entityManager.remove(rndEnt); // didnt work
}
}
SomeEntity barEntity = new SomeEntity()
someEntityRepository.save(barEntity);
someMoreDbOPs();
}
i hope this pseudo code helps to describe what i am trying to do.
thanks in advance for any help...
Special handling of ConstraintViolationException after failed insert in JPA transaction
Aucun commentaire:
Enregistrer un commentaire