What is a “best practice” for deciding between using EntityChangedEvent
listeners vs. the various annotated methods (preUpdate
, postUpdate
, etc) in the Entity classes themselves? What types of operations would be best handled in one vs. the other?
Hello,
These events differs by moments they sent and by available objects and information in them.
Let’s look on them in order of their sending for standard workflow in DataManager. I will also describe EntitySavingEvent and audit addon logs creation in order to give a more complete picture.
-
[Jmix] EntitySavingEvent:
- Sent: per-entity before changes for particular entity are registered in persistence context.
- Available: entity, beans.
-
[JPA] PrePersist, PreUpdate, PreRemove:
- Sent: before changes are registered in persistence context.
- Available: entity.
-
[JPA] PostPersist, PostUpdate, PostRemove:
- Sent: after changes are registered in persistence context.
- Available: entity.
-
Entity log creation in case of audit addon added.
-
[Jmix] EntityChangedEvent before commit (handled by
@EventListener
)- Sent: after changes are registered in persistence context but before transaction commit.
- Available: entity id, list of changed fields and old values, beans.
-
[Jmix] EntityChangedEvent after commit (handled by
@TransactionalEventListener
)- Sent: when transaction is already commited.
- Available: entity id, list of changed fields and old values, beans.
As we can see, there are two groups of events: JPA events and Jmix events.
Thus, in response to your question:
JPA Events are provided by persistence api and:
- available in both
EntityManager
andDataManager
, - sutiable for simple operations with current entity.
Jmix Events
- available in
DataManager
only, - allow more complex operations when access to beans or list of field changes needed,
-
EntityChangedEvent
is sent after audit data is already persisted which allows to consider it too.
Regards,
Dmitry
4 Likes