當數據發生變化時,沒有從數據庫獲取回調的JPA機制。
唯一的選擇是建立你自己的變化檢測。通常,您會首先檢測添加,刪除哪些實體以及哪些實體仍然存在。對於一旦仍然存在,您將需要檢查它們是否被更改,因此實體需要使用equals()
方法。 實體是由它的主鍵確定,所以你需要得到集中的所有主鍵,一旦你有,你可以很容易地使用番石榴的Sets
方法生產的3臺的添加,刪除,和現有的(之前和現在), 喜歡這個。
List<MyEntity> old = new ArrayList<>(); // load from the DB last time
List<MyEntity> current = new ArrayList<>(); // loaded from DB now
Map<Long, MyEntity> oldMap = old.stream().collect(Collectors.toMap(MyEntity::getId, Function.<MyEntity>identity()));
Map<Long, MyEntity> currentMap = current.stream().collect(Collectors.toMap(MyEntity::getId, Function.<MyEntity>identity()));
Set<Long> oldKeys = oldMap.keySet();
Set<Long> currentKeys = currentMap.keySet();
Sets.SetView<Long> deletedKeys = Sets.difference(oldKeys, currentKeys);
Sets.SetView<Long> addedKeys = Sets.difference(currentKeys, oldKeys);
Sets.SetView<Long> couldBeChanged = Sets.intersection(oldKeys, currentKeys);
for (Long id : couldBeChanged) {
if (oldMap.get(id).equals(currentMap.get(id))) {
// entity with this id was changed
}
}