【问题标题】:Selecting from view and inserting into table Spring JPA从视图中选择并插入表 Spring JPA
【发布时间】:2021-05-05 23:04:15
【问题描述】:

我有两个实体,分别称为 Student 和 Course。它们以以下格式存储在表中

学生

id first_name last_name
1 johnny goode
2 jane doe
3 ted jones

课程

id name subject
1 Calculus math
2 Biology science
3 Chemistry science

Student 和 Course 具有存储在名为 Student_Course 的表中的多对多关系

学生课程

student_id course_id
1 1
2 3

我有一个名为 v_student_course 的 Student_Course 视图,它包含 student_id、course_id 和主题(从课程表中检索)。

v_student_course

student_id course_id subject
1 1 Math
2 3 Science

在我的 Springboot 应用程序中,我有一个 Student 类和一个 Course 类,它们分别看起来像这样

@NoArgsConstructor
@AllArgsConstructor
@Table(name = "Student")
public class Student {
    @GeneratedValue(generator = "generator")
    @Column(name = "id")
    protected @Id int id;

    @Column(name = "first_name")
    protected String firstName;

    @Column(name = "last_name")
    protected String lastName;

    //getters and setters left out for this example
}
@NoArgsConstructor
@AllArgsConstructor
@Table(name = "Course")
public class Course{
    @GeneratedValue(generator = "generator")
    @Column(name = "id")
    protected @Id int id;

    @Column(name = "name")
    protected String name;

    @Column(name = "subject")
    protected String subject;

    //getters and setters left out for this example
}

我必须通过显示学生分配的课程来表示学生和课程之间的多对多关系。但是,所有选择都必须使用视图 v_student_course 完成,所有插入/更新都必须使用表 Student_Course 完成。

  1. 我应该使用 ManyToMany 注释来做到这一点吗?但是,我注意到如果学生没有与课程相关联,这将导致 NullPointerExceptions。或者我应该为桥关系创建一个名为 StudentCourse.java 的单独类?

  2. 我如何声明选择必须来自与插入/更新不同的表/视图?

【问题讨论】:

    标签: java spring spring-boot jpa spring-data-jpa


    【解决方案1】:

    我通过将此代码添加到 Student 类来解决这个问题

    @ManyToMany(fetch = FetchType.LAZY, targetEntity = Course.class)
    @JoinTable(name = "v_student_course",
        joinColumns = { @JoinColumn(name = "student_id", referencedColumnName = "id") },
        inverseJoinColumns = { @JoinColumn(name = "course_id", referencedColumnName = "id")})
    protected List<Course> courses = new ArrayList<>();
    

    我将此代码添加到课程类中

    @ManyToMany(mappedBy = "courses")
    protected List<Student> students = new ArrayList<>();
    

    然后我将它添加到我的 StudentRepository 界面

    @Modifying
    @Query (
        value = "INSERT INTO student_course (student_id, course_id) "
                "VALUES (:studentId, :courseId)",
        nativeQuery = true
    )
    public void saveStudentCourse(@Param("studentId") String studentId,
                                  @Param("courseId") String courseId);
    

    现在每当我搜索学生时,它也会从 v_student_course 中选择与学生相关的课程,但是当我插入新的学生课程关联时,它会直接插入到表中。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-12-05
      • 2018-12-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-05-26
      相关资源
      最近更新 更多