Hibernate 自定义属性访问器和脏检查

问题描述 投票:0回答:2

我有一个自定义属性访问器,它可以在将值设置在我的对象上之前修改它。问题是该对象被检测为脏。有没有办法重置对象的脏度?

hibernate properties
2个回答
0
投票

可能您需要的是使用

@Access(AccessType.FIELD)

例如

 @Access(AccessType.FIELD)
 public String getStringValue()
 {
   return this.stringValue != null ? stringValue : "";
 }

在这种情况下,Hibernate 将使用字段值而不是 getter 进行脏检查。


0
投票
    @PostConstruct
protected void init() {
    SessionFactoryImpl sessionFactory = emf.unwrap(SessionFactoryImpl.class);
    EventListenerRegistry registry = sessionFactory.getServiceRegistry().getService(EventListenerRegistry.class);
    registry.getEventListenerGroup(EventType.FLUSH_ENTITY).appendListener(customDefaultFlushEntityEventListener);
}

公共类 CustomDefaultFlushEntityEventListener 扩展 DefaultFlushEntityEventListener{

@Override
protected void dirtyCheck(final FlushEntityEvent event) throws HibernateException {
    super.dirtyCheck(event);
    excludeIgnoreDirtyPropertiesFromDirtyCheck(event);
}

private void excludeIgnoreDirtyPropertiesFromDirtyCheck(FlushEntityEvent event) {
    String[] propertyNames = event.getEntityEntry().getPersister().getPropertyNames();
    int[] dirtyProperties = event.getDirtyProperties();
    Object[] propertyValues = event.getPropertyValues();
    
    if(dirtyProperties == null) {
        return;
    }
    
    List<String> ignoreDirtyPropertiesList = FieldUtils.getFieldsListWithAnnotation(event.getEntity().getClass(), IgnoreDirtyProperty.class)
    .stream().map(Field::getName)
    .distinct().collect(Collectors.toList());
    
    List<Integer> newDirtyPropertiesList = new ArrayList<>();       
    
    for(int dirtPropertyIdex :  dirtyProperties) {
        
        if(!ignoreDirtyPropertiesList.contains(propertyNames[dirtPropertyIdex])  && !(propertyValues[dirtPropertyIdex] instanceof List)) {
            newDirtyPropertiesList.add(dirtPropertyIdex);
        }
        
    }
    
    int[] newDirtyPropertyArray = newDirtyPropertiesList.stream().mapToInt( index -> index).toArray();
    event.setDirtyProperties(newDirtyPropertyArray);
    
}

}

忽略脏字段:

@IgnoreDirtyProperty @Column(name = "published") Boolean published;

© www.soinside.com 2019 - 2024. All rights reserved.