Reputation: 5852
I am developing Java EE project with embedded database using JPA ORM. My question is...
When I create @ManyToMany fields in two Entities, I have to create association entity too, or it will do container for me?
Course entity snippet
Public class Course implements Serializable {
...
@Id
@GeneratedValue(strategy=GenerationType.IDENTITY)
private long id;
@ManyToMany
@JoinTable(name="course_user", joinColumns={@JoinColumn(name="course_id", referencedColumnName="id")},
inverseJoinColumns={@JoinColumn(name="user_id", referencedColumnName="id")})
private List<User> enrolledStudents;
...
User Entity snippet
public class User implements Serializable {
private static final long serialVersionUID = 1L;
...
@Id
@GeneratedValue(strategy=GenerationType.IDENTITY)
private long id;
@ManyToMany(mappedBy="enrolledStudents")
private List<Course> enrolledCourses;
...
So is this everything I need or not? Thank you for answers!
Upvotes: 0
Views: 173
Reputation: 23226
That will work but see here:
Hibernate Best Practices: Avoiding Many-To-Many and 'exotic' relationships
At some point you will most likely want to save additional info about this relationship (enrollment date for example?) So you may as well create the 'join entity' up front to save refactoring later.
Upvotes: 1
Reputation: 1
Yes, this is sufficient. Look at examples at http://en.wikibooks.org/wiki/Java_Persistence/ManyToMany
Upvotes: 0
Reputation: 1
Yes its all you need... if you create the database from the code, you will see three tables... Course, User and Course_User witch has the IDs of Couse and User
Upvotes: 0