Callbacks Methods: It is often useful for the application to react to certain events that occur inside the persistence mechanism.
Type | Description |
---|---|
@PrePersist | Executed before the entity manager persist operation is actually executed or cascaded. This call is synchronous with the persist operation. |
@PreRemove | Executed before the entity manager remove operation is actually executed or cascaded. This call is synchronous with the remove operation. |
@PostPersist | Executed after the entity manager persist operation is actually executed or cascaded. This call is invoked after the database INSERT is executed. |
@PostRemove | Executed after the entity manager remove operation is actually executed or cascaded. This call is synchronous with the remove operation. |
@PreUpdate | Executed before the database UPDATE operation. |
@PostUpdate | Executed after the database UPDATE operation. |
@PostLoad | Executed after an entity has been loaded into the current persistence context or an entity has been refreshed. |
Example
@Entity @EntityListeners(class=Audit.class) public class Cat { @Id private Integer id; private String name; private Calendar dateOfBirth; @Transient private int age; private Date lastUpdate; //getters and setters /** * Set my transient property at load time based on a calculation, * note that a native Hibernate formula mapping is better for this purpose. */ @PostLoad public void calculateAge() { Calendar birth = new GregorianCalendar(); birth.setTime(dateOfBirth); Calendar now = new GregorianCalendar(); now.setTime( new Date() ); int adjust = 0; if ( now.get(Calendar.DAY_OF_YEAR) - birth.get(Calendar.DAY_OF_YEAR) < 0) { adjust = -1; } age = now.get(Calendar.YEAR) - birth.get(Calendar.YEAR) + adjust; } } public class LastUpdateListener { /** * automatic property set before any database persistence */ @PreUpdate @PrePersist public void setLastUpdate(Cat o) { o.setLastUpdate( new Date() ); } }
Source
Sem comentários:
Enviar um comentário