package com.yanzuoguang.util.vo; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; /** * 数据库操作对象 * * @param <T> * @author 颜佐光 */ public class DataDaoVo<T> { private List<T> creates = new ArrayList<>(); private List<T> updates = new ArrayList<>(); private List<T> removes = new ArrayList<>(); private Map<String, T> mapNow = new HashMap<>(); /** * 将历史数据映射为HashMap * * @param hisitories 历史数据 * @param keyFunc 获取主键函数 * @param <T> * @return */ private static <T> Map<String, T> getMapHistory(List<T> hisitories, DataDaoKey<T> keyFunc) { // 定义缓存集合 Map<String, T> mapHistory = new HashMap<>(10); // 历史数据处理 if (hisitories != null) { for (T his : hisitories) { String key = keyFunc.getKey(his); mapHistory.put(key, his); } } return mapHistory; } /** * 获取结果 * * @param mapHistory 历史数据映射 * @param nows 当前数据 * @param keyFunc 获取主键函数 * @param <T> * @return */ private static <T> DataDaoVo<T> getResult(Map<String, T> mapHistory, List<T> nows, DataDaoKey<T> keyFunc) { DataDaoVo<T> res = new DataDaoVo<T>(); // 返回集 if (nows != null) { for (T now : nows) { String key = keyFunc.getKey(now); T his = mapHistory.get(key); if (his == null) { res.creates.add(now); res.mapNow.put(key, now); } else { mapHistory.remove(key); boolean isChange = keyFunc.set(his, now); if (isChange) { res.updates.add(his); } res.mapNow.put(key, his); } } } res.removes.addAll(mapHistory.values()); return res; } /** * 初始话对象 * * @param hisitories * @param nows * @param keyFunc */ public static <T> DataDaoVo<T> init(List<T> hisitories, List<T> nows, DataDaoKey<T> keyFunc) { Map<String, T> mapHistory = getMapHistory(hisitories, keyFunc); DataDaoVo<T> res = getResult(mapHistory, nows, keyFunc); return res; } /** * 初始话对象 * * @param hisitories * @param nows * @param keyFunc */ public static <T, M> DataDaoVo<T> init(List<T> hisitories, List<M> nows, DataDaoKeyConvert<T, M> keyFunc) { Map<String, T> mapHistory = getMapHistory(hisitories, keyFunc); List<T> toNows = new ArrayList<>(10); if (nows != null) { for (M m : nows) { T t = keyFunc.convert(mapHistory, m); toNows.add(t); } } DataDaoVo<T> res = getResult(mapHistory, toNows, keyFunc); return res; } /** * 需要创建的对象 * * @return */ public List<T> getCreates() { return creates; } /** * 需要修改的对象 * * @return */ public List<T> getUpdates() { return updates; } /** * 需要删除的对象 * * @return */ public List<T> getRemoves() { return removes; } /** * 所有需要修改和更新的对象 * * @return */ public Map<String, T> getMapNow() { return mapNow; } }