使用 BeanItem 属性。您必须自己比较值,但您在每个属性的循环中进行比较(请参阅源代码中的方法“between”)。您所需要的只是可以用作 BeanItem 的数据类,或者是 BeanItem 本身。在 UI 中,您需要拥有具有原始数据的对象和具有更改的原始数据的对象。这是我用来提取两个数据版本之间更改的类:
public class Diff implements Iterable<DiffEntry>{
public static class DiffEntry{
public final Object propertyId;
public final Object oldValue;
public final Object newValue;
public DiffEntry(Object propertyId, Object oldValue, Object newValue) {
super();
this.propertyId = propertyId;
this.oldValue = oldValue;
this.newValue = newValue;
}
}
public static <T> Diff between(T oldPojo, T newPojo) {
//HERE WE EXTRACT WHAT WAS CHANGED
// this could also take BeanItems directly if data are BeanItems
Diff diff = new Diff();
BeanItem<T> oldBean = new BeanItem<T>(oldPojo);
BeanItem<T> newBean = new BeanItem<T>(newPojo);
for(Object propertyId : oldBean.getItemPropertyIds()) {
Object oldValue = oldBean.getItemProperty(propertyId).getValue();
Object newValue = newBean.getItemProperty(propertyId).getValue();
if(oldValue == null) {
if(newValue != null) {
DiffEntry entry = new DiffEntry(propertyId, oldValue, newValue);
diff.add(entry);
}
}
else if(newValue == null) {
DiffEntry entry = new DiffEntry(propertyId, oldValue, newValue);
diff.add(entry);
}
else if(!oldValue.equals(newValue)) {
DiffEntry entry = new DiffEntry(propertyId, oldValue, newValue);
diff.add(entry);
}
else {
//old and new values are equal
}
}
return diff;
}
private final Map<Object, DiffEntry> entries = new HashMap<>();
public Diff() {
}
private void add(DiffEntry entry) {
this.entries.put(entry.propertyId, entry);
}
/**
* Returns true if this diff contains difference for specified property id
* @param propertyId id of property we test for difference
* @return true if this diff contains difference for specified property id
*/
public boolean contains(Object propertyId) {
return this.entries.containsKey(propertyId);
}
/**
* Returns true if there are no differencies
* @return true if there are no differencies
*/
public boolean isEmpty() {
return this.entries.isEmpty();
}
@Override
public Iterator<DiffEntry> iterator() {
return entries.values().iterator();
}
}
在您的上下文中“跟踪用户所做的更改,并且只保存必要的”这将完成这项工作,但它不会阻止处理 UI 中的所有字段,因为这是在读取所有数据之后完成的来自字段并存储在newPojo中!