Reputation: 525
I have an entity called recInfo, which contains a few info about creation and modification of entries in a few entities all together.
At this moment, the implementation is done with a setter, so every time I want to add a entry in one of these entities I have to create a new recInfo and set it to the recInfo field of my entity.
I was thinking about adding a listener to this few entities that, every time someone created a new one or modified it saved the timestamp, the user who created it (with sessionContext.getCallerPrincipal().toString();
I've looked in the documentation, but I found it quite hard to understand how to apply the listeners there to a change in an entity!
Upvotes: 0
Views: 1325
Reputation: 141
JPA callbacks are used for this purpose.
public class EntityListener {
@PrePersist
@PreUpdate
public void setRecInfo(Entity entity) {
RecInfo recInfo = new RecInfo();
// TODO set recInfo fields
entity.setRecInfo(recInfo);
}
}
@Entity
@EntityListeners (value = {EntityListener.class})
public class Entity {
private RecInfo recInfo;
public RecInfo getRecInfo() { return recInfo };
public void setRecInfo(RecInfo recInfo) { this.recInfo = recInfo };
}
Upvotes: 2