I am getting an exception
object references an unsaved transient instance – save the transient instance before flushing
thrown in the following code:
public void addThing(String key, String someData) {
Thing thing = new Thing();
booking.setData(someData);
booking.setParent(this);
bookings.put(key, thing);
}
The Parent mapping is:
@ElementCollection(fetch=FetchType.EAGER)
@Column(name="thing", nullable=false)
@MapKeyColumn(name="key")
@JoinColumn(name="parent_id")
protected Map<String, Thing> things = Maps.newHashMap();
The child (‘Thing’) mapping is:
@ManyToOne
private Parent parent;
According to the Hibernate manual:
There is no cascade option on an
ElementCollection, the target objects are always persisted, merged, removed with their parent.
But – before I changed to the new @ElementCollection mapping so solve a problem where I was getting apparently phantom elements returned for a query, this code worked correctly.
I know I can save the element separately and then make a reference, but I prefer to have it done automatically, and I thought that was the way it is supposed to work. Any ideas?
@ElementCollectionis not supposed to be used with collections of entities; it’s used with collections of@Embeddable. IfThingis an entity, you don’t use@ElementCollection, you use@OneToMany.From the javadoc for
@ElementCollection: