Optional<Order> 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<Long> itemIds = orderRequest.getItems().stream().map(id -> id.getId()).collect(Collectors.toSet());
for (ItemRequest itemRequest : orderRequest.getItems()) {
Iterator<Item> 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());
}
}
}
}
}