What is the best way to delete an entity and then refresh all of the places in the application that have a reference to it? I have two references to a particular entity and when I delete the entity I want the other location updated. Here is the scenario:
Entity A has a collection (List) of Entity B (OneToMany).
I obtain an instance of Entity A via a first query.
I obtain an instance of Entity B via a second query.
I delete the instance of Entity B which was obtained from the second query (EntityManager.remove).
Now, the collection of Entity B in the instance of entity A is not correct (it should contain one less instance of Entity B).
How do I update the collection in entity A?
I've tried using EntityManager.refresh on Entity A but the collection is not refreshed and iterating over the collection results in an exception:
I've also tried requerying Entity A, but the collection is not refreshed (I suppose it continues to use a cached copy).
Do I need to remove the object from the collection directly (List.remove)? I would have thought that the refresh would have done it, especially since I have (cascade = CascadeType.ALL) set on the OneToMany relationship annotation.
Note: If I add a new Entity B then a EntityManager.refresh on Entity A DOES work.
Thanks for your response. To answer your question: I am removing and then flushing:
I'm using a stateful session bean and calling the removeEntity method using an expression language method expression from a JSF page. I'm obtaining a new reference to the entity before removing because the entity that is being passed into the method is detached (I think). I tried to use the merge method instead of getReference but if I do then when I call remove I get an exception: