hibernate annotation bi-directional mapping
Posted
by
smithystar
on Stack Overflow
See other posts from Stack Overflow
or by smithystar
Published on 2010-01-12T22:44:28Z
Indexed on
2012/09/22
9:38 UTC
Read the original article
Hit count: 178
I'm building a web application using Spring framework and Hibernate with annotation and get stuck with a simple mapping between two entities.
I'm trying to create a many-to-many relationship between User and Course. I followed one of the Hibernate tutorials and my implementation is as follows:
User class:
@Entity
@Table(name="USER")
public class User {
private Long id;
private String email;
private String password;
private Set<Course> courses = new HashSet<Course>(0);
@Id
@GeneratedValue
@Column(name="USER_ID")
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
@Column(name="USER_EMAIL")
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
@Column(name="USER_PASSWORD")
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
@ManyToMany(cascade = CascadeType.ALL)
@JoinTable(name = "USER_COURSE", joinColumns =
{ @JoinColumn(name = "USER_ID") },
inverseJoinColumns = { @JoinColumn(name = "COURSE_ID") })
public Set<Course> getCourses() {
return courses;
}
public void setCourses(Set<Course> courses) {
this.courses = courses;
}
}
Course class:
@Entity
@Table(name="COURSE")
public class Course {
private Long id;
private String name;
@Id
@GeneratedValue
@Column(name="COURSE_ID")
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
@Column(name="NAME")
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
The problem is that this implementation only allows me to go one way
user.getCourses()
What do I need to change, so I can go in both directions?
user.getCourses()
course.getUsers()
Any help would be appreciated.
© Stack Overflow or respective owner