且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

可以向@ManyToMany Hibernate 额外表添加额外字段吗?

更新时间:2023-12-02 09:02:58

如果在链接表 (STUDENT_COURSE) 上添加额外的字段,则必须根据 skaffman 的回答或其他方法选择一种方法,如下所示.

If you add extra fields on a linked table (STUDENT_COURSE), you have to choose an approach according to skaffman's answer or another as shown bellow.

有一种方法,其中链接表 (STUDENT_COURSE) 的行为类似于 @Embeddable,根据:

There is an approach where the linked table (STUDENT_COURSE) behaves like a @Embeddable according to:

@Embeddable
public class JoinedStudentCourse {

    // Lets suppose you have added this field
    @Column(updatable=false)
    private Date joinedDate;

    @ManyToOne(fetch=FetchType.LAZY)
    @JoinColumn(name="STUDENT_ID", insertable=false, updatable=false)
    private Student student;

    @ManyToOne(fetch=FetchType.LAZY)
    @JoinColumn(name="COURSE_ID", insertable=false, updatable=false)
    private Course course;

    // getter's and setter's 

    public boolean equals(Object instance) {
        if(instance == null)
            return false;

        if(!(instance instanceof JoinedStudentCourse))
            return false;

        JoinedStudentCourse other = (JoinedStudentCourse) instance;
        if(!(student.getId().equals(other.getStudent().getId()))
            return false;

        if(!(course.getId().equals(other.getCourse().getId()))
            return false;

        // ATT: use immutable fields like joinedDate in equals() implementation
        if(!(joinedDate.equals(other.getJoinedDate()))
            return false;

        return true;
    }

    public int hashcode() {
        // hashcode implementation
    }

}

因此您将同时拥有学生和课程课程

So you will have in both Student and Course classes

public class Student {

    @CollectionOfElements
    @JoinTable(
        table=@Table(name="STUDENT_COURSE"),
        joinColumns=@JoinColumn(name="STUDENT_ID")
    )
    private Set<JoinedStudentCourse> joined = new HashSet<JoinedStudentCourse>();

}

public class Course {

    @CollectionOfElements
    @JoinTable(
        table=@Table(name="STUDENT_COURSE"),
        joinColumns=@JoinColumn(name="COURSE_ID")
    )
    private Set<JoinedStudentCourse> joined = new HashSet<JoinedStudentCourse>();

}

记住:@Embeddable 类的生命周期绑定到拥有的实体类(Student 和 Course),所以要注意它.

remember: @Embeddable class has its lifecycle bound to the owning entity class (Both Student and Course), so take care of it.

建议:由于@ManyToMany 映射的一些限制 - 级联操作,Hibernate 团队支持这两种方法(@OneToMany(skaffman 的回答)或@CollectionsOfElements).

advice: Hibernate team suppports these two approachs (@OneToMany (skaffman's answer) or @CollectionsOfElements) due some limitations in @ManyToMany mapping - cascade operation.

问候,