Many to Many hibernate inverse side ignored

前端 未结 2 1803
离开以前
离开以前 2020-12-10 06:05

Hi am reading the hibernate documentation.

http://docs.jboss.org/hibernate/annotations/3.5/reference/en/html/entity.html

A many-to-many associ

2条回答
  •  执笔经年
    2020-12-10 06:20

    Suppose you have the following entities:

    @Entity
    public class Student {
        @ManyToMany
        private Set courses;
        ...
    }
    
    @Entity
    public class Course {
        @ManyToMany(mappedBy = "courses")
        private Set students;
        ...
    }
    

    The owner side is Student (because it doesn't have the mappedBy attribute). The inverse side is Course ((because it has the mappedBy attribute).

    If you do the following:

    Course course = session.get(Course.class, 3L);
    Student student = session.get(Student.class, 4L);
    student.getCourses().add(course);
    

    Hibernate will add an entry for student 4 and course 3 in the join table because you updated the owner side of the association (student.courses).

    Whereas if you do the following:

    Course course = session.get(Course.class, 3L);
    Student student = session.get(Student.class, 4L);
    course.getStudents().add(student);
    

    nothing will happen, because uou updated the inverse side of the association (course.students), but neglected to updated the owner side. Hibernate only considers the owner side.

提交回复
热议问题