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

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());
                    }
                }
            }
        }
    }

Are there any code examples left?
Made with love
This website uses cookies to make IQCode work for you. By using this site, you agree to our cookie policy

Welcome Back!

Sign up to unlock all of IQCode features:
  • Test your skills and track progress
  • Engage in comprehensive interactive courses
  • Commit to daily skill-enhancing challenges
  • Solve practical, real-world issues
  • Share your insights and learnings
Create an account
Sign in
Recover lost password
Or log in with

Create a Free Account

Sign up to unlock all of IQCode features:
  • Test your skills and track progress
  • Engage in comprehensive interactive courses
  • Commit to daily skill-enhancing challenges
  • Solve practical, real-world issues
  • Share your insights and learnings
Create an account
Sign up
Or sign up with
By signing up, you agree to the Terms and Conditions and Privacy Policy. You also agree to receive product-related marketing emails from IQCode, which you can unsubscribe from at any time.
Creating a new code example
Code snippet title
Source