How can I manage to create a many-to-many relationship. The generated entity will have extra attributes.
I开发者_StackOverflow 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.
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:
- an
@EmbeddedId
, where you define a separate class holding the two parts of the primary key. That class must be@Embeddable
- 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)
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;
}
精彩评论