@Transactional @Override public void saveScheduleForProfessional( int idProfessional, int idCareSession, List<ScheduleEntity> schedules) { CareSessionEntity careSession = careSessionDao.findById(idCareSession); ProfessionalEntity professional = professionalDao.findById(idProfessional); Validator.shouldBeFound(careSession); Validator.shouldBeFound(professional); List<ScheduleEntity> alreadyInDB = scheduleDao.findByProfessionalByCareSession(idProfessional, idCareSession); // Remove the schedules (with its appointments) no longer present List<Integer> idsToRemove = getIdsFromAnotContainedInB(alreadyInDB, schedules); if (!idsToRemove.isEmpty()) { scheduleDao.deleteSchedulesWithAppointments(idsToRemove); scheduleDao.flush(); } // get list of IDs on alreadyInDB but schedules, to erase them for (ScheduleEntity se : schedules) { se.setProfessional(professional); se.setCareSession(careSession); } // create or update scheduleDao.saveAll(schedules); scheduleDao.flush(); }