java – Hibernate:永远不会调用MyInterceptor#onFlushDirty
发布时间:2020-12-15 07:36:40 所属栏目:Java 来源:网络整理
导读:问题:为什么永远不会调用MyInterceptor#onFlushDirty? 我在xml配置中扩展AbstractEntityManagerFactoryBean bean id="myEntityManagerFactory" parent="abstractEntityManagerFactoryBean" abstract="true" property name="entityInterceptor" bean class=
问题:为什么永远不会调用MyInterceptor#onFlushDirty?
我在xml配置中扩展AbstractEntityManagerFactoryBean <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; } } 更新:[解释为什么自定义脏策略看起来不是我的方式] 我想在每次更改文件夹实体EXCEPT folderPosition中的内容时更新修改时间戳.同时,folderPosition应该是持久的而不是瞬态的(意味着导致实体变脏). 由于我使用的是Spring Transactional和Hibernate模板,因此有一些细微差别: 1)我无法更新每个setter末尾的修改时间戳,如: 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)我无法手动调用setModified,因为它有大约25个字段,并且每个字段的setXXX分散在整个应用程序中.我没有权力进行重构. @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(); } .... } 解决方法
您需要扩展findDirty方法而不是onFlushDirty.通过参考GitHub工作示例,查看
this tutorial以获取详细说明.
(编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |