Model structure in many to many relationship

自闭症网瘾萝莉.ら 提交于 2020-01-11 11:45:12

问题


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.


回答1:


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).




回答2:


http://docs.oracle.com/javaee/1.4/tutorial/doc/BMP3.html

This might be useful to you. As I have similar type of problem few days ago..



来源:https://stackoverflow.com/questions/14219954/model-structure-in-many-to-many-relationship

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!