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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1153409/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-12 00:17:38  来源:igfitidea点击:

Can add extra field(s) to @ManyToMany Hibernate extra table?

javahibernate

提问by Am1rr3zA

I have these two class(table)

我有这两个类(表)

@Entity
@Table(name = "course")
public class Course {

    @Id
    @Column(name = "courseid")
    private String courseId;
    @Column(name = "coursename")
    private String courseName;
    @Column(name = "vahed")
    private int vahed;
    @Column(name = "coursedep")
    private int dep;
    @ManyToMany(fetch = FetchType.LAZY)
    @JoinTable(name = "student_course", joinColumns = @JoinColumn(name = "course_id"),  inverseJoinColumns = @JoinColumn(name = "student_id"))
    private Set<Student> student = new HashSet<Student>();
//Some setter and getter

and this one:

和这个:

    @Entity
    @Table(name = "student")
    public class Student {

        @Id
        @Column(name="studid")
        private String stId;
        @Column(nullable = false, name="studname")
        private String studName;
        @Column(name="stmajor")
        private String stMajor;
        @Column(name="stlevel", length=3)
        private String stLevel;
        @Column(name="stdep")
        private int stdep;

        @ManyToMany(fetch = FetchType.LAZY)
        @JoinTable(name = "student_course"
                ,joinColumns = @JoinColumn(name = "student_id")
                ,inverseJoinColumns = @JoinColumn(name = "course_id")
        )
        private Set<Course> course = new HashSet<Course>();
//Some setter and getter

After running this code an extra table was created in database(student_course), now I wanna know how can I add extra field in this table like (Grade, Date , and ... (I mean student_course table)) I see some solution but I don't like them, Also I have some problem with them:

运行此代码后,在数据库(student_course)中创建了一个额外的表,现在我想知道如何在该表中添加额外的字段,例如(Grade、Date 和 ...(我的意思是 student_course 表))我看到了一些解决方案,但是我不喜欢它们,而且我对它们有一些问题:

First Sample

第一个样品

采纳答案by Arthur Ronald

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) 上添加额外字段,则必须根据 skaffman 的答案或其他方法选择一种方法,如下所示。

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

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

@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

因此,您将在 Student 和 Course 类中都有

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>();

}

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

请记住:@Embeddable 类的生命周期绑定到拥有的实体类(Student 和 Course),因此请注意它。

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

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

regards,

问候,

回答by skaffman

The student_course table is there purely to record the association between the two entities. It is managed by hibernate, and can contain no other data.

student_course 表纯粹是为了记录两个实体之间的关联。它由休眠管理,不能包含其他数据。

The sort of data you want to record needs to be modelled as another entity. Perhaps you could a one-to-many association between Course and StudentResult (which contains the grade, etc), and then a many-to-one association between StdentResult and Student.

您要记录的数据类型需要建模为另一个实体。也许您可以在 Course 和 StudentResult(包含成绩等)之间建立一对多关联,然后在 StdentResult 和 Student 之间建立多对一关联。

回答by mcintyre321

Drop the many-to-many, create a class called StudentCourseRelationship and set up one to manys on Student and Course to the StudentCourseRelationship.

删除多对多,创建一个名为 StudentCourseRelationship 的类,并在 Student 和 Course 上设置一对多到 StudentCourseRelationship。

You can put all sorts of things on it, like DateEnrolled, DateKickedOut etc. etc.

你可以在上面放各种各样的东西,比如 DateEnrolled、DateKickedOut 等等。

IMO the many-to-many mapping is a bit of a con.

IMO 多对多映射有点骗人。

回答by azerole

The accepted answer unfortunately doesn't work for me, hibernate generates the join table in a weird way (all join columns are duplicated). However the variant with dedicated entity for the join table works fine. Here it is described in great detail: http://www.mkyong.com/hibernate/hibernate-many-to-many-example-join-table-extra-column-annotation/

不幸的是,接受的答案对我不起作用,hibernate 以一种奇怪的方式生成连接表(所有连接列都是重复的)。然而,连接表专用实体的变体工作正常。这里有很详细的描述:http: //www.mkyong.com/hibernate/hibernate-many-to-many-example-join-table-extra-column-annotation/