前臺傳來的新數據與數據庫中的舊數據比較更新算法

工做中遇到一個很小的功能,發現寫好還有點難度,通過一夜的思考,把成果記錄下。 java

問題: 數據庫

數據庫中保存了一些數據,前臺更新操做傳來新的數據。如何比較差別,進行更新。如: app

前臺傳來1,2,3,數據庫中有3,5。則須要在數據庫中增長1,2;在數據庫中刪除5;原有數據3不變。 spa

解決方法一: code

先把數據庫中原的數據所有清空,而後把前臺的數據所有執行插入。 rem

這種方法簡單,很容易理解,以及判斷及正確性。缺點是若是原數據庫數據較多,則重複刪除後增長,則效率不高。 get

解決方法二: hash

查詢原數據庫中的數據,作爲待刪除的列表。 it

遍歷前臺傳來的數據,對每個在上邊待刪除列表中查詢,若是存在,則說明此條數據要在數據庫中保留。則從待刪除列表中移除。若不存在,則說明須要在數據庫中增長一條數據,放到一個新建列表中。 class

完成遍歷後一次性刪除待刪除列表中的數據,插入新建列表中的數據。


List<AppSystem> appSystem_deleteList = appSystemDao.getByAppkey(app
		.getAppkey());
List<AppSystem> appSystem_addList = new ArrayList<AppSystem>();
if (sysStr != null && !"".equals(sysStr)) {
	// 組成hashmap只爲加速查詢
	Map<String, AppSystem> appSystem_searchMap = new HashMap<String, AppSystem>();
	for (AppSystem as : appSystem_deleteList) {
		appSystem_searchMap.put(as.getSystemid().toString(), as);
	}
	// 依次將前臺傳來的新值進行循環檢查
	String[] systemIds = sysStr.split(",");
	for (String systemId : systemIds) {
		if (appSystem_searchMap.containsKey(systemId)) {
			// 若是匹配到,則說明仍然須要,則從刪除列表去去除
			appSystem_deleteList.remove(appSystem_searchMap
					.get(systemId));
		} else {
			// 未匹配到,則說明須要增長
			appSystem_addList.add(new AppSystem(app.getAppkey(), Long
					.parseLong(systemId)));
		}
	}
}
appSystemDao.batchAdd(appSystem_addList);
appSystemDao.batchDelete(appSystem_deleteList);
相關文章
相關標籤/搜索