【问题标题】:Automatically updating Many-to-Many tables with unique coloumns自动更新具有唯一列的多对多表
【发布时间】:2012-01-07 14:17:15
【问题描述】:

虽然我写了这个问题,但我想出了一个解决方案,但我还是要问。也许有更简单的方法。

我想从两个表中创建一个关联表。 我们称它们为学生和课程。两者都有一个 ID 和一个唯一的名称。
我想要的是第三张表(student_id 到 course_id),当我插入正在上课的学生时,它会自动更新。

这几乎是我找到here: Hibernate Many-to-Many with Annotations 的以下示例,但我将@Table 注释更改为
@Table(name = "STUDENT", uniqueConstraints = {@UniqueConstraint(columnNames = {"STUDENT_NAME" })})
课程也是如此。

我插入第一个学生

Set<Course> courses = new HashSet<Course>();
courses.add("Math); courses.add("Science");

Student alice = new Student("alice", courses);

另一个学生来了

Student bob= new Student("bob", courses);

它崩溃是因为课程表中已经存在科学和数学课程,并且student_to_course表不会更新。

我所知道的是在课程表中查询具有此名称的课程。如果有,我将其添加到学生课程中,否则添加新的。

List<Course> list = session.createCriteria(Course.class)
            .add(Restrictions.eq("courseName", "Maths")).list();
if (list.size() > 0){
   courses.add(list.get(0));
}
else {
    courses.add(new Course("Maths"));           
}
s.setCourses(courses);

所以这行得通,但我认为必须有更好的方法来做到这一点。
如果表中已经有同名的课程,有没有办法告诉hibernate从课程表中将课程添加到学生?

【问题讨论】:

    标签: java hibernate many-to-many


    【解决方案1】:

    你做对了,别无他法。

    除了这个场景不太现实。大多数情况下,可用课程列表是预先知道的,您只能在创建学生时从可用课程中进行选择。 UI 通常会提出一个多选框,您必须在其中选择课程,并且您不会使用课程名称,而是使用课程 ID(或直接使用课程实体)来引用所选课程。

    因此,该方法将如下所示:

    public Student createStudent(String studentName, Set<Long> courseIds)
    

    或者像这样:

    public Student createStudent(String studentName, Set<Course> courses)
    

    在第一种情况下,获取一组课程的最简单和最快的方法是循环访问课程 ID 并调用 session.load(courseId) 以获取对课程的引用,甚至无需访问数据库。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-09-07
      • 1970-01-01
      • 1970-01-01
      • 2021-09-07
      • 1970-01-01
      • 2015-10-03
      • 1970-01-01
      • 2022-01-07
      相关资源
      最近更新 更多