gpt4 book ai didi

java - 1 :M relationship in Hibernate and cascading operations

转载 作者:行者123 更新时间:2023-11-30 06:38:09 24 4
gpt4 key购买 nike

表 SUBCOURSE 引用 COURSE类(class)(编号,名称)SUBCOURSE(id, course_id, name)

所以,1:M。

Hibernate 为类(class)生成:

    @OneToMany(fetch = FetchType.LAZY, mappedBy = "course", cascade = CascadeType.ALL)    public Set getSubCourses() {        return this.subCourses;    }

它生成的子类(class)

    @ManyToOne(fetch = FetchType.LAZY)    @JoinColumn(name = "course_id", nullable = false)    public Course getCourse() {        return this.course;    }

现在的问题是级联没有按预期工作。我想创建一个 SubCourse 对象的集合(Set),填充它然后将它绑定(bind)到 Course 对象的 setSubCourses()。然后简单地持久化 Course 对象。

不过,在 Subcourses 表中有 ManyToOne 东西,我需要手动setCourse() 在添加到每个对象的集合之前。如果我不这样做,持久化 Course 对象及其集合时会引发异常。

你能给我推荐什么?

附言或者这可能是游戏的一部分?手动设置每个 child 的父对象?

最佳答案

看来这是游戏的一部分。引用 Hibernate 书中的内容(指的是 Item 是父项,Bid 是子项的示例):

If you only call anItem.getBids().add(bid), no changes are made persistent! You get what you want only if the other side, aBid.setItem(anItem), is set correctly. This is consistent with the behavior in Java without Hibernate: If an association is bidirectional, you have to create the link with pointers on two sides, not just one. It’s the primary reason why we recommend convenience methods such as addBid() — they take care of the bidirectional references in a system without container- managed relationships.

上面提到的类是

public class Item {
...
private Set bids = new HashSet();
public void setBids(Set bids) {
this.bids = bids;
}
public Set getBids() {
return bids;
}
public void addBid(Bid bid) {
bid.setItem(this);
bids.add(bid);
}
...
}

关于java - 1 :M relationship in Hibernate and cascading operations,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2600021/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com