spring delete objest from database that are not in your object list

Solutions on MaxInterview for spring delete objest from database that are not in your object list by the best coders in the world

showing results for - "spring delete objest from database that are not in your object list"
Lorenzo
10 Apr 2020
1Optional<Order> orderFromDb = orderRepo.findById(id);
2
3    if(CollectionUtils.isNotEmpty(orderRequest.getItems()))
4
5    {
6        // if there are less items in update request than database
7        if (orderRequest.getItems().size() < orderFromDb.getItems().size()) {
8            Set<Long> itemIds = orderRequest.getItems().stream().map(id -> id.getId()).collect(Collectors.toSet());
9            for (ItemRequest itemRequest : orderRequest.getItems()) {
10                Iterator<Item> item = orderFromDb.getItems().iterator();
11                Item i;
12                while (item.hasNext()) {
13                    i = item.next();
14                    if (!itemIds.contains(i.getId())) {
15                        item.remove();
16                        continue;
17                    }
18                    if (i.getId() == itemRequest.getId()) {
19                        i.setName(itemRequest.getName());
20                    }
21                }
22            }
23        } else {
24            // if there are more or same items in update request and database
25            for (ItemRequest itemRequest : orderRequest.getItems()) {
26                // assuming for newly added items id will not be there(db should generate)
27                if (itemRequest.getId() == null) {
28                    Item item = new Item();
29                    item.setName(itemRequest.getName());
30                    item.setOrder(orderFromDb);
31                    orderFromDb.getItems().add(item);
32                    continue;
33                }
34                for (Item item : orderFromDb.getItems()) {
35                    if (item.getId() == itemRequest.getId()) {
36                        item.setName(request.getName());
37                    }
38                }
39            }
40        }
41    }
42
similar questions