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