Java – Hibernate: myinterceptor #onflushdirty will never be called
Question: why never call myinterceptor #onflushdirty?
I extend abstractentitymanagerfactorybean in XML configuration
<bean id="myEntityManagerFactory" parent="abstractEntityManagerfactorybean" abstract="true"> <property name="entityInterceptor"> <bean class="xxxx.MyInterceptor"/> </property> </bean> <bean id="abstractEntityManagerfactorybean" class="xxxx.MyEntityManagerfactorybean"/>
MyEntityManagerfactorybean
public class MyEntityManagerfactorybean extends AbstractEntityManagerfactorybean implements LoadTimeweaverAware { private Interceptor entityInterceptor; public Interceptor getEntityInterceptor() { return entityInterceptor; } public void setEntityInterceptor(Interceptor interceptor) { entityInterceptor = interceptor; } }
MyInterceptor:
public class MyInterceptor extends EmptyInterceptor { public MyInterceptor() { System.out.println("init"); // Works well } // PROBLEM - is never called @Override public boolean onFlushDirty(Object entity,Serializable id,Object[] currentState,Object[] prevIoUsState,String[] propertyNames,Type[] types) { if (entity instanceof File) { ..... } return false; } }
Update: [explain why customizing dirty policies doesn't seem to be my way]
I want to update the modification timestamp every time I change the content in the folder entity excel folderposition At the same time, folderposition should be persistent rather than transient (meaning that it causes the entity to become dirty)
Because I use spring transactional and Hibernate templates, there are some subtle differences:
1) I cannot update the modification timestamp at the end of each setter, such as:
public void setXXX(XXX xxx) { //PROBLEM: Hibernate templates collect object via setters,//means simple get query will cause multiple 'modified' timestamp updates this.xxx = xxx; this.modified = new Date(); }
2) I can't call setmodified manually because it has about 25 fields, and setXXX of each field is scattered throughout the application I have no right to restructure
@Entity public class Folder { /** * GOAL: Changing of each of these fields except 'folderPosition' should cause * 'modified' timestamp update */ private long id; private String name; private Date created; private Date modified; private Integer folderLocation; @PreUpdate public void preUpdate() { //PROBLEM : change modified even if only location field has been changed! //PROBLEM: need to kNow which fields have been updated! modified = new Date(); } .... }
Solution
You need to extend the finddirty method instead of onflushdirty See this tutorial for details by referring to the GitHub working example