使用BeanItem屬性。你必須自己比較值,但是你要在每個屬性的循環中執行它(請參閱源代碼中的「之間」方法)。所有你需要的是可以用作BeanItem的數據類,或者是BeanItem本身。在用戶界面中,您需要擁有包含原始數據和對象的原始數據對象並進行更改。下面是I類用於提取數據的兩個版本之間的更改:
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之後完成的!
就像一個提示:當你使用像hibernate或eclipselink這樣的ORM框架時,他們會關心保存更改後的值。 – nexus
我正在研究hibernate envers,但也想知道vaadin是否有自己的方式(或者可能是GWT)。 – abden003