I have an Entity which contains a collection of another Entity which itself references the same class in a collection, with the following mappings:
@Entity
@Table(name="parents")
public class Parent {
@Id
@GeneratedValue
private long id;
@ElementCollection
@Cascade(org.hibernate.annotations.CascadeType.ALL)
private Set<Child> children;
public Parent() {}
public Parent(Set<Child> children) {
this.children = children;
}
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public Set<Child> getChildren() {
return children;
}
public void setChildren(Set<Child> children) {
this.children = children;
}
@Entity
@Table(name="children")
public static class Child {
@Id
@GeneratedValue
private long id;
private String name;
@ElementCollection
@Cascade(org.hibernate.annotations.CascadeType.ALL)
private Set<Child> dependencies;
public Child() {}
public Child(String name) {
this.name = name;
dependencies = new LinkedHashSet<>();
}
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public getDependencies() {
return dependencies;
}
public setDependencies(Set<Child> dependencies) {
this.dependencies = dependencies;
}
}
}
But when I try to save it, I get a: java.lang.IllegalStateException: org.hibernate.TransientObjectException: object references an unsaved transient instance - save the transient instance before flushing
exception
I've read in another post that I should use @Cascade(CascadeType.ALL)
annotation, but as you can see, I tried doing so and it didn't solve my problem.
Please help me understand what's wrong with these mappings