JPA通过中间实体获取实体

时间:2018-08-13 21:30:39

标签: jpa spring-data-jpa

我有3个实体,分别是“学生”,“课程”和“学生课程”,

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

    @Id
    @GeneratedValue
    private Integer id;

    private String fullName;
}

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

    @Id
    @GeneratedValue
    private Integer id;

    private String courseName;
}


@Entity
@Table(name = "student_course")
public class StudeCourse {

    @Id
    @GeneratedValue
    private Integer studentId;
    private Integer courseId;
    private String extraColumn;
}

限制:有几个限制

  1. 一个学生只能选一门课程或根本没有一门课程
  2. 需要一个额外的实体(StudentCourse)来保存主键为学生ID的关系
  3. StudentCourse是必需的,因此不能跳过
  4. 如果已注册一个课程实体,请获取具有课程实体的学生
如果分配了某些魔术代码,则需要

帮助来检索“学生课程”。

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

    @Id
    @GeneratedValue
    private Integer id; 
    private String fullName;

    // this is not correct code but just what I want
    @JoinEntity(entity=StudentCourse, column="courseId")
    private Course course;
}

1 个答案:

答案 0 :(得分:0)

  

StudentCourse是必需的,因此不能跳过

好吧,让我们一起工作。

  

一个学生只能选一门课程或根本没有一门课程

表示@OneToOneStudent之间存在StudentCourse关系。


使用给定的信息,以下实体模型将起作用:

@Entity
@Table(name = "student")
public class Student {
    @Column(name = "id")
    @Id
    @GeneratedValue
    private Integer id;

    @Column(name = "full_name")
    private String full_name;

    @OneToOne
    @PrimaryKeyJoinColumn
    private StudentCourse studentCourse;
}

@Entity
@Table(name = "student_course")
public class StudentCourse {
    @Column(name = "id")
    @Id
    @GeneratedValue
    private Integer id;

    @JoinColumn(name = "id", nullable = false, updatable = false)
    @MapsId
    @OneToOne
    private Student student;

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

    ...
}

快速浏览:

    @OneToOne字段上的
  1. Student.studentCourse表示每个Student只能有一个StudentCourse,而没有其他内容。
  2. @PrimaryKeyJoinColumn字段上的
  3. Student.studentCourse表示Student的主键列的值应用作相关实体的外键,即{{1} }。
  4. StudentCourse字段上的
  5. @OneToOne表示每个StudentCourse.student只能有一个StudentCourse
  6. Student字段上的
  7. @MapsId表示应将StudentCourse.student的主键列用作关联的联接列。

要检查学生是否已分配课程,只需检查StudentCourse是否为student.getStudentCourse() != null即可获得分配的课程。