1

I have 2 entities: Class(of students) and Student. A student can be in many classes(like in college) and a class has many students. The problem is how to ensure that this entity, generated in the middle, has 2 primary keys, the ids of each other entity (Student and Class). I need to know how to create it using annotations. I use EJB3 and JPA Annotations in the project.

vaultah
  • 44,105
  • 12
  • 114
  • 143
Lu4nation
  • 13
  • 4

2 Answers2

3

First, you don't need a middle entity. You have two entities and a join table between them.

You need a middle entity only if you have additional information about the relation - for example a StudentClass may have timesAbsent column.

In case you really need the third entity, you can have:

  1. an @EmbeddedId, where you define a separate class holding the two parts of the primary key. That class must be @Embeddable
  2. an @IdClass which will let you specify two @Id fields. You'll again need another class to hold the two fields representing the key.

See this question for which option to choose.

Note that you thus have a composite primary key, not two primary keys (which you can't have)

Community
  • 1
  • 1
Bozho
  • 588,226
  • 146
  • 1,060
  • 1,140
0

I know how to make this happen using hibernate. May be it'll help.

Make the collection type Set.

 public class CollegeClass { 
     private Set<Student> students;
 }

 public class Student { 
     private Set<CollegeClass> classes; 
 }
Aleksey
  • 1,309
  • 2
  • 10
  • 12