2

Is the execution order of the queries whithin a transaction always the same of the jpa method call order in the code?

I have an entity Element and the entity Order . On the Order entity I have a @ManyToOne relation that is Unidirectional . On the Order table there is a FK reference to Element table but on the Element entity there is no OneToMany relationship to order.

The deleteElement method starts by calling a method to remove all the order of an element (elementService.deleteOrderElement(element); it's called on a diffrenrent EJB).

Then It removes the element itself entityManager.remove(element); .

My problem is that sometimes in production enviroment I recieve a foreign constraint violation error, as if the delete element query it has been called before the delete order queries. Is possible that Hibernate just mixeup the queries since there is only a Unidirectional reletionship? I was not able to replicate the error in test enviroment.

This is an extraction of the method code. The actual method is more complex but this is the critic part.

@TransactionAttribute(TransactionAttributeType.REQUIRED)
public void deleteElement(Set<Long> elementIds,String utente) {
        .....
        Long id = null;
        Iterator<Long> it = idDpi.iterator();
        while (it.hasNext()) {
            Element element =entityManager.find(Element.class, it.next());

            ...
            elementService.deleteOrderElement(element);
            ....
            entityManager.remove(element );
            log.debug("Aggiorna tabella auditing - rimozione dpi");
    }
}
Panciz
  • 2,183
  • 2
  • 30
  • 54

1 Answers1

0

Bumped into a similar issue in my code recently. There is not so much information about it but looks like your issue is in hibernate SQL execution order when flushing to the database. It's mentioned in documentation of AbstractFlushingEventListener.

There is some explanation here. And a more detailed discussion about it there.

Basically, the fix is to call flush() manually or use update in my case since I had delete and then insert operations which caused a duplicate key violation exception since hibernate executed insert first.

amisiuryk
  • 195
  • 3
  • 12