繁体   English   中英

如何在不使用@Mapsid 的情况下使用 JPA Hibernate 将 3 个实体加入表中

[英]How can I join 3 entities in a table using JPA Hibernate without using @Mapsid

[this is my DB design](https://i.stack.imgur.com/7ckz4.png)
[Users entitie](https://i.stack.imgur.com/8mMfR.png)
[Roles entitie](https://i.stack.imgur.com/ACYNB.png)
[Project entitie](https://i.stack.imgur.com/ZJXKC.png)

Users 和 Has 之间的关系不需要是单向的

使用这个复合键类,我们可以创建实体类,它模拟连接表:

@Entity
class CourseRating {

    @EmbeddedId
    CourseRatingKey id;

    @ManyToOne
    @MapsId("studentId")
    @JoinColumn(name = "student_id")
    Student student;

    @ManyToOne
    @MapsId("courseId")
    @JoinColumn(name = "course_id")
    Course course;

    int rating;
    
    // standard constructors, getters, and setters
}


This code is very similar to a regular entity implementation. However, we have some key differences:

We used @EmbeddedId to mark the primary key, which is an instance of the CourseRatingKey class.
We marked the student and course fields with @MapsId.
@MapsId means that we tie those fields to a part of the key, and they're the foreign keys of a many-to-one relationship. We need it because, as we mentioned, we can't have entities in the composite key.

After this, we can configure the inverse references in the Student and Course entities as before:

class Student {

    // ...

    @OneToMany(mappedBy = "student")
    Set<CourseRating> ratings;

    // ...
}

class Course {

    // ...

    @OneToMany(mappedBy = "course")
    Set<CourseRating> ratings;

    // ...
}

请注意,还有一种使用复合键的替代方法:@IdClass 注释。

3.4. 更多特征 我们将与 Student 和 Course 类的关系配置为 @ManyToOne。 我们可以这样做是因为使用新实体,我们在结构上将多对多关系分解为两个多对一关系。

为什么我们能够做到这一点? 如果我们仔细检查前一个案例中的表,我们可以看到它包含两个多对一关系。 换句话说,RDBMS 中没有任何多对多关系。 我们将使用连接表创建的结构称为多对多关系,因为这就是我们建模的对象。

此外,如果我们谈论多对多关系会更清楚,因为这是我们的意图。 同时,连接表只是一个实现细节; 我们并不真正关心它。

此外,此解决方案还有一个我们尚未提及的附加功能。 简单的多对多解决方案在两个实体之间创建关系。 因此,我们无法将关系扩展到更多实体。 但是我们在这个解决方案中没有这个限制:我们可以对任意数量的实体类型之间的关系进行建模。

例如,当多个教师可以教授一门课程时,学生可以评价特定教师教授特定课程的方式。 这样一来,评级将成为三个实体之间的关系:学生、课程和教师。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM