Question: How to check which fields has been changed inside method annotated with @PreUpdate
?
OPTIONAL: if the answer to the question above is "It's impossible, than maybe there are another ways to solve my problem"
I want automatically update modified
Tourist
's field each time we change something in it.
Except the situation when we modify only location
. Means if we change location
only - it should be persisted, but modified
mustn't be changed.
Already present code:
@Entity
public class Tourist {
private long id;
private String firstName;
private String lastName;
private Date created;
private Date modified;
private String location;
@PreUpdate
public void preUpdate() {
modified = new Date(); //PROBLEM : change modified even if only location field has been changed!
}
....
}
Updated: After some investigations I found that I can solve it with help of interceptors (extend EmptyInterceptor
):
public class TouristInterceptor extends EmptyInterceptor{
Session session;
private Set updates = new HashSet();
public void setSession(Session session) {
this.session=session;
}
public boolean onFlushDirty(Object entity,Serializable id,
Object[] currentState,Object[] previousState,
String[] propertyNames,Type[] types)
throws CallbackException {
if (entity instanceof Tourist){
if (somethingChangedExceptLocation())
updates.add(entity);
}
return false;
}
But disadvantage of this approach is to intercept everything when you need to intercept the single entity.
Updated Questions:
- How to intercept only Tourist entity flush calls?
- Is that possible to do the same with help of events? Means
PreUpdateEvent
which contains new and old state