1

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.

Hossein Nasr
  • 1,436
  • 2
  • 20
  • 40

1 Answers1

2

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);
Wilder Valera
  • 986
  • 9
  • 11
  • Unfortunately, I did that. But since I simplified my code, I removed it. the interesting thing is that the problem occurs only when I call `iterator()`. Otherwise, everything is fine. – Hossein Nasr Jan 10 '18 at 08:51
  • This exception occurs when trying to use the Domain property with the data model having detached state. You need to explicitly fetch the Domain Object using the property and use this fetched object further using session.load(yourTransientObject) – Praveen Shendge Aug 08 '18 at 15:05