【问题标题】:It is necessary to take data from a table that is generated automatically and there is no model and no repository for it有必要从自动生成的表中获取数据,并且没有模型和存储库
【发布时间】:2021-11-04 04:35:09
【问题描述】:

我有一个学生模型

@Entity
public class Student {
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Long id;
    private String name;
    @ManyToMany
    @JoinTable (name="student_university",
            joinColumns=@JoinColumn (name="student_id"),
            inverseJoinColumns=@JoinColumn(name="university_id"))
    private List<University> universities;

还有大学模式

@Entity
public class University {
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private long id;
    @Column
    private String name;
    @ManyToMany
    @JoinTable(name="student_university",
            joinColumns=@JoinColumn(name="university_id"),
            inverseJoinColumns=@JoinColumn(name="student_id"))
    private List<Student> students;

我有 2 个模型和 2 个存储库。由于连接是ManyToMany,所以会自动生成3表。如果没有模型和存储库,我如何从这个新表中获取数据?也许您可以从控制器以某种方式编写请求并将结果传递给模板?

SQL 学生

大学 SQL

student_university SQL

【问题讨论】:

  • 你可以使用 SQL。问题是为什么要查询这个表,因为只有两个外键。
  • 你能展示如何在控制器中编写sql查询并将结果传递给模板吗?我不明白该怎么做
  • 我需要做一个附加表格,然后这个表格中的数据将被保存到这个表中。将有 2 个下拉列表。 1,我选择一个学生,第二,一个大学
  • 不需要查询这个中间表来完成你在上面评论中描述的“加法表”。您可以与实体 Student 和 University 合作
  • 如何与他们合作?我在我的问题中插入了 SQL

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


【解决方案1】:

假设由于您使用的是 spring-boot,您已经为您的实体创建了相关的 JpaRepositories,例如studentRepositoryuniversityRepository

从数据库中加载选定的(在下拉列表中)学生和大学,例如 假设从下拉列表中选择的学生有#id:10,从另一个下拉列表中选择的大学有#id:45

Long studentId = 10L; //retrieve the real value from your controller's request
Student student = studentRepository.findById(studentId);

Long univerityId = 45L; //retrieve the real value from your controller's request
University univeristy = universityRepository.findById(univerityId);

然后将大学添加到学生的大学列表并保存到 DB

student.getUniversities().add(university); //make sure your university list is not null else you will get a null pointer exception here
university.getStudents().add(student); // you can also add the student to the university's students list
studentRepository.save(student);

保存student_university 表后应该有一条新记录,其中包含学生和大学的ID。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-06-09
    • 2012-12-06
    • 2016-04-11
    相关资源
    最近更新 更多