Java EE 8 and Angular
上QQ阅读APP看书,第一时间看更新

Entity listeners

The listeners can be put to use for performing interception on entity life cycle operations. We can also inject CDI managed beans into an entity listener for performing any additional processing. Here are the seven life cycle callback annotations that can be used:

The Task entity has an entity listener associated with it, thus during its life cycle events, the listener callback methods would be invoked. If there is more than one listener, then the invocation is done in the order of the listener declaration:

@Entity
@Table(name="task_detail")
@EntityListeners({TaskAudit.class})
public class Task extends MappedSuperEntity {
// code omitted
}

During each life cycle event of the Task entity, our TaskAudit class methods would be invoked, which are listening to the event. Thus, to listen to the post persist event, the following code declares a trackChanges method with the @PostPersist annotation:

public class TaskAudit {
@PersistenceContext private EntityManager em;
@PostPersist public void trackChanges(MappedSuperEntity entity)
{ ... }
}

While the listeners are handy to use for simple cases, they fall short for handling more complex requirements. There are modules, such as Hibernate Envers, which provide support for auditing capabilities with more capable features, but these are not part of the standard JPA specification.