سؤال

I have the following method in a JPA EntityListener:

@PostPersist
    void onPostPersist(Pli pli) {
        EvenementPli event = new EvenementPli();
        event.setPli(pli);
        event.setDateCreation(new Date());
        event.setDateEvenement(new Date());
        event.setType(TypeEvenement.creation);
        event.setMessage("Création d'un pli");
        event.persist();
    }

Basically, I am trying to create an event by persisting an instance of EvenementPli each time an instance of the Pli entity is persisted.

The trouble is that the by the time event.persist(); is called the Pli row is not in the database which causes Mysql to complain about the constraint...

Can anyone please help?

هل كانت مفيدة؟

المحلول

Appropriate solution is to redesign application such a way, that persisting EvenementPli happens somewhere else than in @PostPersist callback method of other entity. According JPA 2.0 specification such a operations are not guaranteed to work in lifecycle callback methods:

In general, the lifecycle method of a portable application should not invoke EntityManager or Query operations, access other entity instances, or modify relationships within the same persistence context.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top