开发者

Have to persist both sides of @OneToMany self-join

开发者 https://www.devze.com 2023-03-13 05:42 出处:网络
I have a bi-directional @OneToMany self-join on a JPA 2.0 entity and I find that I have to persist both sides of the relationship for the changes to be reflected in the persistence context.In this sit

I have a bi-directional @OneToMany self-join on a JPA 2.0 entity and I find that I have to persist both sides of the relationship for the changes to be reflected in the persistence context. In this situation I am merging the parent and persisting the child.

I manually maintain both sides of the relationship by adding to the child collection when setting the parent. I thought that this would be enough and that I would not have to persist both sides.

Is this behaviour correct, or am I doing something wrong? I have tried setting various combinations of cascade options on both sides of the relationship to no avail.

@Entity
public class Context extends AbstractEntity implements Serializable {

    private static final long serialVersionUID = 1L;
    private String name;
    @ManyToOne
    private Context parent;
    @OneToMany(mappedBy = "parent")
    private List<Context> children;
    @OneToMany
    private List<Task> tasks;

    private void addChild(Context child) {
        this.children.add(child);
    }

    public void setParent(Context parent) {
        this.parent = parent;
        this.parent.addChild(this);
    }

//Getters and setters
}


//@ManagedBean making data changes

public void createContext() {
        context.setParent((Context) selectedNode.getData());
        contextFacade.edit(context.getParent());
        contextFacade.create(context);
        //Display result
    }
开发者_开发知识库
0

精彩评论

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

关注公众号