/** * When an installation is created or updated, the categories are passed without IDs. * This method solve this issue by checking for existing categories and updating them (otherwise it would * persist a new object). * @param entity to merge the categories for * @param categoriesToMerge are the categories to merge with the existing one */ private void mergeCategories(Installation entity, Set<Category> categoriesToMerge) { if (entity.getCategories() != null) { final List<String> categoryNames = convertToNames(categoriesToMerge); final List<Category> existingCategoriesFromDB = categoryDao.findByNames(categoryNames); // Replace json dematerialised categories with their persistent counter parts (see Category.equals), // by remove existing/persistent categories from the new collection, and adding them back in (with their PK). categoriesToMerge.removeAll(existingCategoriesFromDB); categoriesToMerge.addAll(existingCategoriesFromDB); // and apply the passed in ones. entity.setCategories(categoriesToMerge); } }