Reputation: 313
I have a ManyToMany association between two Entities: COURSE and STUDENT. They are associated through a STUDENT_COURSE_MAP association table.
Course.java:
@Entity
@Table(name="COURSE")
public class Course implements java.io.Serializable {
@ManyToMany(
mappedBy="courses",
cascade={CascadeType.PERSIST, CascadeType.MERGE}
)
private List<Student> students = Collections.emptyList();
// Rest of the class, getters, setters etc
}
Student.java:
@Entity
@Table(name="STUDENT")
public class Student implements java.io.Serializable {
@ManyToMany(
targetEntity=Course.class,
cascade = { CascadeType.PERSIST, CascadeType.MERGE }
)
@JoinTable(
name="STUDENT_COURSE_MAP",
joinColumns=@JoinColumn(name="STUDENT_REF"),
inverseJoinColumns=@JoinColumn(name="COURSE_REF")
)
private Set<Course> courses = Collections.emptySet();
// Rest of the class, getters, setters etc
}
I want to add a student (id=11) list for one particular course (id=77) as follows (transaction is already begun):
// Create new list and add a student to it
Student student_11 = (Student) session.get(Student.class.getName(), 11);
List<Student> studentsList = new ArrayList<Student>(1);
studentsList.add(student_11);
// Now, set the list of students in the course
Course course_77 = (Course) session.get(Course.class.getName(), 77);
course_77.setStudents(studentsList);
I save it using the following code:
session.flush();
session.getTransaction().commit();
However, the association - course_77 and student_11 - does not get persisted to the database. There are no insert statements generated in the hibernate log.
I even tried calling session.saveOrUpdate(course_77)
. Only the following is logged when saveOrUpdate
is called:
allowing proxied method [saveOrUpdate] to proceed to real session
persistent instance of: org.whatra.tradecog.db.entity.Artist
ignoring persistent instance
object already associated with session: [Course#77]
Hints/tips/solutions are much appreciated.
Note 1: The whole persistence thing works just fine for me when I create new Course and Student objects and save. What does not work is when I retrieve existing Course and existing Student objects and add a new association between them.
Upvotes: 5
Views: 10753
Reputation: 313
Here's what was wrong. It turns out I was saving only one side of the association. This is what I should have done:
// Create new list and add a student to it
Student student_11 = (Student)session.get(Student.class.getName(), 11);
Course course_77 = (Course) session.get(Course.class.getName(), 77);
List studentsList = new ArrayList(1);
studentsList.add(student_11);
Set coursesList = new HashSet(1);
coursesList.add(course_77);
course_77.setStudents(studentsList);
// THIS IS WHAT'S WRONG - I MISSED THIS NEXT LINE
student_11.setCourses(coursesList);
I found the answer at http://en.wikibooks.org/wiki/Java_Persistence/Relationships (look under 'Common Problems').
Upvotes: 6