Create Entity Listener
Entity listeners can be used to react to various changes in an entity, for example, when saving an entity to log this save action. Using the Entity Listener Wizard, you can generate the required entity listener and then just insert the code to be executed after the event is triggered. A total of 7 events are supported.
-
PrePersist - Executed before the entity is persisted. Also executed when persisting sub-entities (Cascade).
-
PostPersist - executed after the entity has been persisted (INSERT). Also executed when persisting sub-entities (Cascade).
-
PreRemove - executed before the entity is deleted. Also executed when deleting sub-entities (Cascade).
-
PostRemove - executed after the entity is deleted. It is also executed when sub-entities are deleted (Cascade).
-
PreUpdate - Will be executed before the entity is updated.
-
PostUpdate - executed after the entity has been updated.
-
PostLoad - Executed after the entity is loaded or updated.
-
Click Add Listener in the entity editor.
-
Specify a name for the entity listener at Name or accept the name suggestion, e.g. CarListener.
-
For Callback methods, specify for which changes in the entity corresponding callback methods should be generated, e.g. PrePersist.
-
Click Finish.
-
In Project Management > Entities select the generated class CarListener.java and add the corresponding action code to the callback method.
-
Result:
CarListener.java - The wizard generates the class CarListener.java in Project Management > Entities and sets the annotation @EntityListeners(CarListener.class) in the entity Car.
package com.company.examples.entities;
import javax.persistence.PrePersist;
public class CarListener {
@PrePersist
public void prePersist(Car car) {
// Action before the entity is persisted
}
}
|