休眠和级联操作中的1:M关系 [英] 1:M relationship in Hibernate and cascading operations

查看:108
本文介绍了休眠和级联操作中的1:M关系的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

SUBCOURSE表参考COURSE 课程(ID,姓名) SUBCOURSE(id,course_id,name)

Table SUBCOURSE references COURSE COURSE(id, name) SUBCOURSE(id, course_id, name)

所以,1:M.

Hibernate为课程生成:

Hibernate generates for Course:


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

它为Subcourse生成

for Subcourse it generates


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

现在问题是级联无法按预期进行. 我想创建一个SubCourse对象(集合)的集合,填充它,然后 将其绑定到Course对象的setSubCourses().然后只需保留Course对象即可.

Now the problem is that cascading does not work as expected. I want to create a collection of SubCourse objects (Set), fill it and then bind it to setSubCourses() of Course object. Then simply persist the Course object.

尽管,Subcourses表中有ManyToOne,但我需要手动 setCourse(),然后添加到每个对象的集合中.如果我不这样做, 在将Course对象及其集合持久化时会引发异常.

Though, having ManyToOne thing in a Subcourses table, I need to manually setCourse() before adding to collection on each object. If I do not do so, an exception is raised when persisting Course object with its collection.

你能推荐我什么?

P.S.也许这是游戏的一部分?手动设置每个孩子的父对象?

P.S. or maybe this is part of the game? setting a parent object of every child by hand?

推荐答案

这似乎是游戏的一部分.引用Hibernate的书中的内容(请参考一个示例,其中Item是父级,Bid是子级):

It seems that this is part of the game. Quote from the Hibernate book (referring to an example where Item is the parent and Bid is the child):

如果仅调用anItem.getBids().add(bid),则不会永久保留任何更改! 仅当另一侧aBid.setItem(anItem)正确设置时,您才能获得所需的内容. 这与没有Hibernate的Java中的行为一致:如果有关联 是双向的,您必须创建在两侧具有指针的链接,而不仅仅是 一.这是我们推荐便捷方法的主要原因,例如 addBid()-它们负责在没有容器的系统中的双向引用- 托管关系.

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);
  }
  ...
}

这篇关于休眠和级联操作中的1:M关系的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆