Model structure in many to many relationship

2019-03-01 01:31发布

问题:

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