删除数据库中与同步数据冗余的数据(多对多)
思路
- 先获取冗余的数据
- 从关联的中间表删除
- 删除出冗余的数据
如果不删除中间表的数据,数据库中有外键,不能删除冗余数据
private void deleteSurplusHosts(List<Host> hostList) {
        List<Host> hosts = hostService.getAll();
        List<HostGroup> hostGroupList = hostGroupService.getAllGroups();
        List<Host> deletedHostList = new ArrayList<>();
        logger.debug("判断获取的计算机不为空");
        if (hosts.isEmpty()) {
            return;
        }
        logger.debug("获取移除的计算机");
        for (Host host : hosts) {
            if (!hostList.contains(host)) {
                deletedHostList.add(host);
            }
        }
        logger.debug("删除关联的中间表");
        for (HostGroup hostGroup : hostGroupList) {
            hostGroup.getHostList().removeIf((host) -> deletedHostList.contains(host));
        }
        hostGroupRepository.saveAll(hostGroupList);
        logger.debug("删除计算机");
        hostRepository.deleteInBatch(deletedHostList);
    }思路清晰其实并不难,主要学习了一下Java中的contains和removeIf
contains
- 描述
从数据库中查询出满足一系列条件的记录,然后以对象的形式封装到List中去。此时假设有两个条件A和B,满足A的记录集和为ListA,满足B的记录集合为ListB,现在要将ListA和ListB合并为一个List,注意ListA和ListB中可能有重复的记录(因为可能某条记录即满足条件A又满足条件B),要过滤掉重复的记录。
俩个对象的属性相等,但俩个对象不应定相等。可能不在一块内存,所以需要重写hashCode()与equals()
- 重写hashCode()与equals()


@Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;
        Host host = (Host) o;
        if (context != host.context) return false;
        return name != null ? name.equals(host.name) : host.name == null;
    }
    @Override
    public int hashCode() {
        int result = name != null ? name.hashCode() : 0;
        result = 31 * result + context;
        return result;
    }重写hashCode()与equals()方法,如果name相同,俩个对象就相同;(上述代码`idea`可自动生成)。
removeIf
- 描述
删除集合中符合条件的成员,empty集合也可以,但是null就炸啦。
- 例如
private static void removeIfTest() {
        List<String> list = Lists.newArrayList("1","12","13","14","15","0");
        System.out.println("初始时:"+ list.toString());
        list.removeIf(s -> s.contains("1"));
        System.out.println("过滤完:" + list.toString());
        }
和过滤filter用法有点相似
循环依赖
最后在启动项目时,使用构造函数注入@Autowired出现了循环依赖
解决:必需俩边都从构造函数中拿出来,单独注入
关于循环依赖在组长的思否中有详细介绍Spring Bean 循环依赖
总结
总结、总结也没什么好说的,就是自己又学到了新知识,又成长了,在此多谢有张喜硕组长给我讲解contains与removeIf
相关推荐
  Jaystrong    2020-08-02  
   gaogaorimu    2020-07-18  
   FanErZong    2020-07-18  
   liwf    2020-07-09  
   thatway    2020-06-28  
   糊一笑    2020-06-27  
   tangjianft    2020-06-25  
   86284851    2020-06-16  
   LUOPING0    2020-06-16  
   sshong    2020-06-12  
   wys    2020-06-10  
   mmyCSDN    2020-05-28  
   fanhuasijin    2020-05-28  
   liuyong00    2020-05-19  
 