Hibernate TransientObjectException on OneToMany with CascadeType.ALL if we call iterator() before save

328 Views Asked by At

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.

1

There are 1 best solutions below

2
On

Your item object needs to have a reference to its parent:

Container container = entityManager.find(Container.class,id);
Item item = new Item();
item.setContainer(container); //needed
container.getItems().add(item);