I have this 2 classes:
@Entity
public class Student extends User {
...
@ManyToMany(mappedBy = "members", fetch = FetchType.EAGER)
private Set<Group> groups;
...
public void addGroup(Group group) {
groups.add(group);
}
}
@Entity
@Table(name = "Group")
public class Group implements Serializable {
...
@ManyToMany(fetch = FetchType.EAGER)
@JoinTable(name = "member_of")
private Set<Student> members;
...
public void addMember(Student student) {
members.add(student);
}
}
This is the session bean which manages their relationships:
@Stateless
public class StudentManager extends AcademicManager implements StudentManagerRemote {
...
@Override
public void requestAnswer(long requestID, RequestAnswer answer) {
Request request = entityManager.find(Request.class, requestID);
if(answer == RequestAnswer.YES) {
Student student = request.getStudent();
Group group = request.getGroup();
group.addMember(student);
student.addGroup(group);
entityManager.flush();
entityManager.clear();
}
}
...
}
It does not update db. Why? I do the same for other relationship, but this is the only ManyToMany I have.
I also tried with a query, but did not work.
EDIT: I edited the code like Mr.J4mes suggested, but it still does not work.
Moreover: why are .flush() and .clear() not necessary?
When you’re calling
group.getMembers(), you are just getting a copy of theSetthat containsStudentfrom theGroupentity. Hence, when you update it, theSetinside yourGroupentity does not get updated. You have 2 choices:Get the
SetfromGroupand set back after updating it:Add a method
addStudentinside theGroupentity & a methodaddGroupinside theStudententity to call in yourrequestAnswermethod. It would be something like this:Besides, you don’t really need to call
em.flush()andem.cancel().