模型结构中的多对多关系 [英] Model structure in many to many relationship

查看:93
本文介绍了模型结构中的多对多关系的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

例如,如果我的数据库中有以下表格,而且学生和课程有很多关系。

 学生
-------
Id(主键)
FirstName
LastName

课程
------
Id(主键)
标题

StudentCourse
-------------
StudentId(外键 - >学生)
CourseId(外键 - >课程)

现在,如果我的模型如下

  public class Student 
{
private int ID;
private String firstName;
private String lastName;

// getter and setter
}

 公共课课程
{
private int ID;
pirvate字符串标题;
// getter and setter
}

所以我的问题是如果我创建只有这两个bean我会遇到什么样的问题?我将遇到什么样的问题以及在哪种情况下?请为这么多关系指定正确的bean结构。




  • 你将无法看到学生 - 课程协会

  • 您将无法从课程导航到课程中的学生(反之亦然)

  • 您删除学生/课程时会有问题,如果它在StudentCourse表中(外包密钥违规)



一般来说:你不想要就像这样。



可能的解决方案:使用ORM系统,如Hibernate,EclipseLink或OpenJPA。然后你可以有一个私人名单< Student>学生; 在你的课程实体(实体在这里比bean,imho更好的名字)和/或私有列表与LT;课程和GT; 学生实体中的课程;



在List<之间建立实际关联;>字段和数据库中的连接表,您需要配置映射(这是ORM用于弥合数据库模式和实体之间差距的配置)。


For example if i have following tables in my database and Student and Course has many to many relationship.

Student
-------
Id (Primary Key)
FirstName
LastName

Course
------
Id (Primary Key)
Title

StudentCourse
-------------
StudentId (Foreign Key -> Student)
CourseId (Foreign Key -> Course)

Now if my model is as follows

public class Student
{
  private int ID;
  private String firstName;
  private String lastName;

  //getter and setter
}

and

public class Course
{
private int ID;
pirvate String title;
//getter and setter
}

So my question is if i create only these two beans what sort of problem will i encounter?What sort of problem will i face and in which condition?And please specify the correct bean structure for such many to many relationship.

解决方案

What problems will you encounter:

  • You won't be able to see the Student - Course associations
  • You won't be able to navigate from a Course to the Students on the Course (and vice-versa)
  • You will have problems deleting a Student/Course, if its in the StudentCourse table (foregin key violation)

Generally: you don't want it like this.

Possible solution: use an ORM system, like Hibernate, EclipseLink or OpenJPA. Then you can have a private List<Student> students; in your Course entity (entity is a better name here than bean, imho), and/or a private List<Course> courses; in the Student entity.

To make the actual association between the List<> fields and the connecting table in the database, you need to configure the mapping (which is the configuration the ORM uses to bridge the gap between the database schema and the entities).

这篇关于模型结构中的多对多关系的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆