Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
576 views
in Technique[技术] by (71.8m points)

jpa 2.0 - Many to Many hibernate inverse side ignored

Hi am reading the hibernate documentation.

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

A many-to-many association is defined logically using the @ManyToMany annotation. You also have to describe the association table and the join conditions using the @JoinTable annotation. If the association is bidirectional, one side has to be the owner and one side has to be the inverse end (ie. it will be ignored when updating the relationship values in the association table):

I understand everything but the last

(ie. it will be ignored when updating the relationship values in the association table).

What does this mean? Example?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Suppose you have the following entities:

@Entity
public class Student {
    @ManyToMany
    private Set<Course> courses;
    ...
}

@Entity
public class Course {
    @ManyToMany(mappedBy = "courses")
    private Set<Student> 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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...