Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Hibernate unsaved instance exception using @ElementCollection

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?

like image 324
gub Avatar asked Jul 03 '11 00:07

gub


1 Answers

@ElementCollection is not supposed to be used with collections of entities; it's used with collections of @Embeddable. If Thing is an entity, you don't use @ElementCollection, you use @OneToMany.

From the javadoc for @ElementCollection:

Defines a collection of instances of a basic type or embeddable class

like image 192
skaffman Avatar answered Sep 21 '22 07:09

skaffman