Reputation: 36640
I've read the documentation and thought I'd be able to do the following....
map my classes as so (which does work)
@Entity
public class ParentEntity
{
...
@OneToMany(mappedBy = "parent")
private List<ChildEntity> children;
...
}
@Entity
public class ChildEntity
{
...
@Id
@Column
private Long id;
...
@ManyToOne
@NotFound(action = NotFoundAction.IGNORE)
@JoinColumn(name = "parent_id")
private ParentEntity parent;
...
}
.. but i want to be able to insert into both tables in one go and thought this would work:
parent = new ParentEntity();
parent.setChildren(new ArrayList<ChildEntity>());
ChildEntity child = new ChildEntity();
child.setParent(parent);
parent.getChildren().add(child);
session.persist(parent);
Can anyone tell me what i'm missing?
Do i need to save the parent first, then add the child and save it again?
thanks.
Upvotes: 1
Views: 128
Reputation: 597026
You have to add @OneToMany(cascade=CascadeType.PERSIST)
. You can also have CascadeType.ALL
which includes persist, merge, delete...
Cascading is the setting that tells hibernate what to do with collection elements when the owning entity is persisted/merged/deleted.
By default it does nothing with them. If the respective cascade type is set, it invokes the same operation for the collection elements that were invoked for the parent.
Upvotes: 2