当前位置: 首页 > 面试题库 >

Hibernate: MyInterceptor#onFlushDirty is never called

姬昊焱
2023-03-14
问题内容

AbstractEntityManagerFactoryBean像这样扩展xml配置

<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;
    }
}

更新:[解释为什么自定义肮脏策略看起来不是我的方式]

modified每当我在Folder实体EXCEPT中更改某些内容时,我都希望更新时间戳folderPosition。同时folderPosition应该是持久的,而不是短暂的(意味着实体变脏)。

由于我使用Spring事务和hibernate模板,因此有一些细微差别:

1)我无法在每个设置器的末尾更新修改后的时间戳,例如:

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。



 类似资料:

相关阅读

相关文章

相关问答