开发者

saving mapped collection in new entity

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 Par开发者_JS百科entEntity 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.


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜