📜  从数据库中删除不在对象列表中的对象 - Java 代码示例

📅  最后修改于: 2022-03-11 14:52:26.883000             🧑  作者: Mango

代码示例1
Optional orderFromDb = orderRepo.findById(id);

    if(CollectionUtils.isNotEmpty(orderRequest.getItems()))

    {
        // if there are less items in update request than database
        if (orderRequest.getItems().size() < orderFromDb.getItems().size()) {
            Set itemIds = orderRequest.getItems().stream().map(id -> id.getId()).collect(Collectors.toSet());
            for (ItemRequest itemRequest : orderRequest.getItems()) {
                Iterator item = orderFromDb.getItems().iterator();
                Item i;
                while (item.hasNext()) {
                    i = item.next();
                    if (!itemIds.contains(i.getId())) {
                        item.remove();
                        continue;
                    }
                    if (i.getId() == itemRequest.getId()) {
                        i.setName(itemRequest.getName());
                    }
                }
            }
        } else {
            // if there are more or same items in update request and database
            for (ItemRequest itemRequest : orderRequest.getItems()) {
                // assuming for newly added items id will not be there(db should generate)
                if (itemRequest.getId() == null) {
                    Item item = new Item();
                    item.setName(itemRequest.getName());
                    item.setOrder(orderFromDb);
                    orderFromDb.getItems().add(item);
                    continue;
                }
                for (Item item : orderFromDb.getItems()) {
                    if (item.getId() == itemRequest.getId()) {
                        item.setName(request.getName());
                    }
                }
            }
        }
    }