在修改数据时候,查找对比两个list中,那些数据需要修改,那些需要删除,那些需要新增

在修改模块的时候 一条数据下有很多子数据,在进行修改的时候子数据也修改了(可能子数据中有修改的,新增的,删除的,没变化的),常用做法是直接把这条数据的子数据都删了,重新把这批子数据给插入数据库。但是有些业务复杂的(比如子数据的id和其他表关联过),这样的话就不可以把之前的子数据都给删掉重新插入了,因为重新插入的主键id不同。

这时候就需要找出这批数据中 需要新增的,删除的,修改的数据 进行相应的操作。

public static void main(String[] args){
        JSONArray messages=new JSONArray();//新数据
        JSONObject j1=new JSONObject();
        j1.put("rcsId","111");
        JSONObject j2=new JSONObject();
        j2.put("rcsId","222");
        JSONObject j3=new JSONObject();
        j3.put("rcsId","333");
        JSONObject j4=new JSONObject();
        j4.put("rcsId","444");
        messages.add(j1);
        messages.add(j2);
        messages.add(j3);
        messages.add(j4);
        List<RcsTopoMessage> beforeMessageList=new ArrayList<>();//原数据
        beforeMessageList.add(new RcsTopoMessage("1","111"));
        beforeMessageList.add(new RcsTopoMessage("2","222"));
        beforeMessageList.add(new RcsTopoMessage("5","555"));
 
 
       /* JSONArray updateArray=new JSONArray();
        JSONArray insertArray=new JSONArray();
        int msgCount=0;
        if(messages!=null&&messages.size()>0){
            msgCount=messages.size();
            for(int i=0;i<messages.size();i++){
                JSONObject msg=messages.getJSONObject(i);
                String rcsId=msg.getString("rcsId");
                if(beforeMessageList.parallelStream().anyMatch(item ->item.getRcsId().equals(rcsId))){//存在 为修改数据
                    updateArray.add(msg);
                }else {//不存在说明是新增的
                    insertArray.add(msg);
                }
            }
        }*/
        //那些是删除的msg?
        List<RcsTopoMessage> delete = beforeMessageList.stream().filter(item ->(messages.parallelStream().noneMatch(tm->item.getRcsId().equals(((JSONObject)tm).getString("rcsId"))))).collect(toList());
        delete.forEach(e->System.out.println("需要删除的"+e.getRcsId()));
        //那些是修改的
        JSONArray update = messages.stream().filter(tm ->(beforeMessageList.parallelStream().anyMatch(item->item.getRcsId().equals(((JSONObject)tm).getString("rcsId"))))).collect(Collectors.toCollection(JSONArray::new));
        update.forEach(e->System.out.println("需要修改的"+((JSONObject)e).getString("rcsId")));
        //那些是新增的
        JSONArray insert = messages.stream().filter(tm ->(beforeMessageList.parallelStream().noneMatch(item->item.getRcsId().equals(((JSONObject)tm).getString("rcsId"))))).collect(Collectors.toCollection(JSONArray::new));
        insert.forEach(e->System.out.println("需要新增的"+((JSONObject)e).getString("rcsId")));
        System.out.println("===========");
    }

在修改数据时候,查找对比两个list中,那些数据需要修改,那些需要删除,那些需要新增