tags:

views:

2317

answers:

1

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.

+1  A: 

Try using:

myEntity.getObjectAList().removeAll(listA);

this will only keep the objects which aren't already in listA.

Also, if you need to do something like this manually in the future, use an iterator:

Iterator<?> it = myEntitiy.getObjectAList().iterator();
while (it.hasNext())
{
    ...
}

Then it.next() will give you the next item in the array, and it.remove() will remove the last value of next() for you, without giving an exception if you keep looping.

If you need to also have the ability to add a new value while looping, consider using listIterator() instead.

Zack
I can't use removeAll() as I need to perform some validation against the elements individually before deleting them.Thanks for the Iterator tip though.
Damo
I think the point of the removeAll was that it would trim the list on your object down to those you need to check for deletion. Then you check all those and remove if allowed. Then you can add all of listA without checking to see if they are already there because you already removed them.
digitaljoel