Java Hibernate:MyInterceptor#onFlushDirty从未被调用
问题:为什么从未调用Java Hibernate:MyInterceptor#onFlushDirty从未被调用,java,spring,hibernate,jpa,orm,Java,Spring,Hibernate,Jpa,Orm,问题:为什么从未调用MyInterceptor#onFlushDirty 我在xml配置中扩展了AbstractEntityManagerFactoryBean,如 <bean id="myEntityManagerFactory" parent="abstractEntityManagerFactoryBean" abstract="true"> <property name="entityInterceptor"> <bean class="xxxx
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"/>
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;
}
}
更新:[解释为什么自定义脏策略看起来不像我的方式] 我希望每次更改
文件夹
实体中的内容时更新修改
时间戳,但文件夹位置
除外。同时,folderPosition
应该是持久的,而不是暂时的(意味着导致实体变脏)
由于我使用Spring事务模板和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();
}
....
}
您需要扩展
finddrity
方法而不是onFlushDirty
。查看GitHub工作示例的详细说明。能否显示要使用此spring填充的自定义EntityManager类configuartion@Vihar我有点进步。但是我的截取器仍然不能像我预期的那样工作。请您看看我更新的问题?@Vihar您的意思是我现在需要删除构造函数吗?@Vihar先前的错误是由于MyEntityManagerFactoryBean的getInterceptor/setInterceptor
主题外缺少。只是为了确保你不会因为打字错误而意外地声明了一个新方法。谢谢你的充分披露!我从中学到了很多。您可以看一下我问题的更新部分吗?只需覆盖findderty,调用super()并从result.Done中删除folderLocation。有关更多详细信息,请查看我的书。
@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();
}
....
}