Enterprise Java Development@TOPIC@
Provide access to persistence lifecycle events
Persistence lifecycle events provided to class methods
@Entity
@Table(name="ORMLISTEN_PERSON")
public class Person {
@Id @GeneratedValue
private long id;
private String name;
@OneToOne(mappedBy="person", optional=true, cascade=CascadeType.ALL)
private Residence residence;
@PrePersist public void prePersist() {
}
@PostPersist public void postPersist() {
}
@PostLoad public void postLoad() {
}
@PreUpdate public void preUpdate() {
}
@PostUpdate public void postUpdate() {
}
@PreRemove public void preRemove() {
}
@PostRemove public void postRemove() {
}
}
Could be used to log or validate instance at certain stages of lifecycle
JPA prohibits calling EntityManager within callback methods
Persistence lifecycle events provided to external class
@Entity
@Table(name="ORMLISTEN_PERSON")
@EntityListeners(Listener.class)
public class Person {
public class Listener {
@PrePersist public void prePersist(Object entity) {
}
@PostPersist public void postPersist(Object entity) {
}
@PostLoad public void postLoad(Object entity) {
}
@PreUpdate public void preUpdate(Object entity) {
}
@PostUpdate public void postUpdate(Object entity) {
}
@PreRemove public void preRemove(Object entity) {
}
@PostRemove public void postRemove(Object entity) {
}
}
Same Listener class may listen to multiple entity types
Good for when Listener has specific purpose that is type-agnostic