问题: 为什么 MyInterceptor#onFlushDirty 永远不会被调用?
Question: Why MyInterceptor#onFlushDirty is never called?
我在像
<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; } }我的拦截器:
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; } }更新:[解释为什么自定义脏策略看起来不像我的方式]
每次我更改 Folder 实体中的某些内容时,我都希望更新 modified 时间戳,除了 folderPosition.同时folderPosition 应该是持久的而不是短暂的(意味着导致实体变脏).
I want update modified timestamp each time I change something in Folder entity EXCEPT folderPosition. In the same time folderPosition should be persistent and not transient (means cause entity to be dirty).
由于我使用 Spring Transactional 和 Hibernate 模板,所以有一些细微差别:
Due I use Spring Transactional and Hibernate Templates, there is some nuances:
1) 我无法在每个 setter 的末尾更新修改后的时间戳,例如:
1) I can't update modified timestamp at the end of each setter like:
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 分散在整个应用程序中.而且我没有能力进行重构.
2) I can't call setModified manually, because it has about 25 fields, and setXXX for each field is scattered across whole app. And I have no power to make refactoring.
@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 工作示例.
You need to extend the findDirty method not onFlushDirty. Check this tutorial for a detail explanation with a reference to a GitHub working example.
更多推荐
休眠:永远不会调用 MyInterceptor#onFlushDirty
发布评论