I have OneToMany Relation in hibernate like below:
class Container {
@OneToMany( cascade = {CascadeType.ALL}, mappedBy = "container", orphanRemoval = true)
List<Item> items;
}
the simplified scenario is that I load a Container
object (container) from the database and try to add an Item
to container.items
like this:
Container container = entityManager.find(Container.class,id);
container.getItems().add(new Item(container));
entityManager.merge(container);
and everything goes fine. But in my case, I want to iterate over items and check something, but when I just call container.getItems().iterator
and save container
like this:
Container container = entityManager.find(Container.class,id);
container.getItems().add(new Item(container));
container.getItems().iterator(); // here is the change
entityManager.merge(container); // here is where exception occured
I get the following error
org.hibernate.TransientObjectException: object references an unsaved transient instance - save the transient instance beforeQuery flushing: mypackage.items
I have no idea why this exception occurs.