A problem that I often face with Hibernate is having a list (call it listA) of objects that I want to persist against an entity (myEntity) but having to first compare them to the existing list on the entity and delete those that aren't in listA.
The simple way to do this is to clear the list on the Entity and just add all of listA to the entity, however I often have to perform some validation on the elements before they are deleted - eg. to check whether this user is allowed to delete them.
My current approach feels awkward:
//Delete the elements that have been removed
//Use toArray to avoid ConcurrentModificationException
for(ObjectA a : myEntity.getObjectAList().toArray(new ObjectA[myEntity.getObjectAList().size()])) {
if(!listA.contains(a)) {
//Check if this element can be deleted
if(canDelete(a)) {
entityManager.remove(a);
myEntity.getObjectAList().remove(a);
}
}
}
//Add the elements that don't already exist
for(ObjectA a : listA) {
if(!myEntity.getObjectAList().contains(a)) {
myEntity.getObjectAList().add(a);
}
}
Any room for improvement?
Thanks.