双向实体是否需要双方在Hibernate中相互添加?

时间:2015-03-03 03:49:43

标签: java hibernate

双向实体(OneToMany,ManyToMany)是否需要双方相互添加才能在Hibernate中正确保存?根据我的经验,他们需要 。只是想确认我的理解。

也就是说,对于下面的权利,是否需要指示的行?

        Student student = new Student("Carl");
        Course course = new Course("Science");
        ReportCard reportCard = new ReportCard("A");

        student.getCourses().add(course);
        student.getReportCards().add(reportCard);

        reportCard.setStudent(student); // <-- Is this required?
        course.getStudents().add(student); // <-- Is this required?

        studentRepository.save(student);

Student.java

@Entity
public class Student { 
    @OneToMany(cascade = CascadeType.ALL, mappedBy = "student")
    private List<ReportCard> reportCards = new ArrayList<ReportCard>();

    @ManyToMany(cascade = CascadeType.ALL)
    @JoinTable(joinColumns = @JoinColumn(name = "student_id"), inverseJoinColumns = @JoinColumn(name = "course_id"))
    private List<Course> courses = new ArrayList<Course>();

    @Column
    private String name;

}

ReportCard.java

@Entity
public class ReportCard {
    @ManyToOne(optional = false)
    @JoinColumn(nullable = false)
    private Student student;

    @Column
    private String grade;
}

Course.java

@Entity
public class Course {
    @ManyToMany(mappedBy = "courses")
    public List<Student> students = new ArrayList<>();

    @Column
    private String name;
}

编辑:用@JoinColumn

替换@Column

2 个答案:

答案 0 :(得分:6)

Hibernate(ad其他JPA实现)关心关联的拥有方。拥有方是没有mappedBy属性的一方。因此,在您的示例中,reportCard.setStudent(student);是必需的,但student.getReportCards().add(reportCard);不是。

但总的来说,确实最好正确设置关联的每一面,以获得对象的连贯图并简单地避免代码中的错误。

请注意,使用JoinColumn注释String字段是错误的。它们不是连接列,而是列。所以你应该用@Column注释它们,虽然如果你没有指定注释的任何属性它也没用。

答案 1 :(得分:0)

除了以上答案外,在二传手中管理此问题可能会有所帮助。在ReportCard.java

public void setStudent(Student student) {
    this.student = student;
    student.setReportCard(this);
}

Student.java中:

void setReportCard(ReportCard reportCard) {
    this.reportCard = reportCard;
}

因此,使用reportCard.setStudent(student);将为您设置双面。