JordyV
JordyV

Reputation: 389

Java DB: bind multiple instances of a class to one instance of another class

I don't really know how to describe this problem (as you tell by the dodgy title), so here's a full description of the problem. I have two classes, Teacher and Class. Each teacher can teach to several classes and each class has several teachers. In Java, we've mapped it like this:

public class Class {
@ManyToMany(mappedBy = "classes")
private List<Teacher> teachers = new ArrayList<>();
}

We have a superclass, User, and two subclasses, Teacher and Student. These classes inherit from the User superclass. So, in our database we have a table called Users which stores all users as teachers or students. Now, students can only be in one class, so they can only have one ClassID stored in the database. But as I said before, teachers can have several classes. So the point is : How am I able to store all the classes that a teacher has in the database? I see Java created an extra table, called User_Class, which is probably ment to store all the different classes a teacher has and vica versa. Problem is that I can't find any documentation about how to work with this.

Can someone please give me a hand here?

Thanks in advance.

Upvotes: 0

Views: 323

Answers (2)

XaviMuste
XaviMuste

Reputation: 304

That approach is based on a composite primary key. This link is about that: how to make a composite primary key (java persistence annotation)

Upvotes: 0

Barranka
Barranka

Reputation: 21047

Before trying to solve this by code, I think you need to understand it from the database point of view.

You are trying to build a many-to-many relationship. This sort of relationship is built by splitting it in two one-to-many relationships.

So, if you have two entities (namely Course and Teacher... I avoid using "classes" to prevent confusion), and one Course can have many Teachers and one Teacher can have many Courses, then a way to create the relation (in the database) would be like this:

Table Courses

courseId     (PK)
courseName

Table Teachers

teacherId    (PK)
teacherName

Table Courses_Teachers

courseId    (FK, PK)
teacherId   (FK, PK)

(PK stands for "primary key", and FK stands for "foreign key")

Hope this little introduction helps you visualize the way to solve your problem.

Upvotes: 1

Related Questions