gpt4 book ai didi

java - 永远不会调用 onFlushDirty Hibernate Interceptor 方法

转载 作者:行者123 更新时间:2023-11-29 05:13:05 26 4
gpt4 key购买 nike

问题: 为什么从未调用 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;
}
}

我的拦截器:

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 应该是持久的而不是暂时的(意味着导致实体变脏)。

由于我使用 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。检查this tutorial引用 GitHub 工作示例的详细说明。

关于java - 永远不会调用 onFlushDirty Hibernate Interceptor 方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27602318/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com