Create Entity Listener

The Entity Listener allows you to respond to the various changes to an entity that are made, e.g. when saving an entity to log this saving action. You can use the Entity Listener wizard to generate the required entity listener so that you only have to enter the code that has to be executed after triggering the event. A total of seven events are supported:

  • PrePersist - Is executed before the entity is persisted. Is also executed when sub-entities are persisted (Cascade).
  • PostPersist - Is executed after the entity has been persisted (INSERT). Is also executed when sub-entities are persisted (Cascade).
  • PreRemove - Is executed before the entity is removed. Is also executed when sub-entities are removed (Cascade).
  • PostRemove - Is executed after the entity has been deleted. Is also executed when sub-entities are removed (Cascade).
  • PreUpdate - Is executed before the entity is updated.
  • PostUpdate - Is executed after the entity has been updated.
  • PostLoad - Is executed after the entity has been loaded or updated.

  1. In the entity editor, click Add Listener.
  2. Define a name for the entity listener under Name or apply the proposed name, e.g. CarListener.
  3. Under Callback methods, define which changes in the entity you want to generate the corresponding callback methods for, e.g. PrePersist.
  4. Click on Finish
  5. Under Project Management Entities, select the generated CarListener.java class and add the corresponding action code under Callback method.
Result:
  • CarListener.java: Under Project Management > Entities, the wizard generates the CarListener.java class and adds the annotation @EntityListeners(CarListener.class) to the Car entity.

    package com.company.examples.entities;
    
    import javax.persistence.PrePersist;
    
    public class CarListener {
    
    	@PrePersist
    	public void prePersist(Car car) {
       
        // Action before the entity is persisted
    
    	}
    }
Note:
  • Generated code: The wizard only works unidirectionally. This means that the generated methods can be edited or removed only in the code.

Hibernate Documentation

XDEV Software Corp. - One Embarcadero Center, San Francisco, CA 94111, US
Copyright © 2015. XDEV Software Corp. All rights reserved.