我有这2个课程:
@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);
}
}
这是管理其关系的会话bean:
@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();
}
}
...
}
它不会更新db。为什么?我也为其他关系做同样的事,但这是我唯一拥有的ManyToMany 我也尝试过查询,但没有用。
编辑:我编辑了像Mr.J4mes建议的代码,但它仍然不起作用。
而且:为什么没有必要使用.flush()和.clear()?
答案 0 :(得分:1)
当您致电group.getMembers()
时,您只是从Set
实体获得了包含Student
的{{1}}的副本。因此,当您更新它时,Group
实体内的Set
不会更新。你有两个选择:
从Group
获取Set
并在更新后退回:
Group
在Set<Student> members = group.getMembers();
members.add(student);
group.setMembers(members);
实体&amp;内部添加方法addStudent
要在Group
方法中调用的addGroup
实体中的方法Student
。它会是这样的:
requestAnswer
此外,您实际上不需要致电@Entity
public class Group implements Serializable {
private Set<Student> members;
public void addMember(Student student) {
this.members.add(student);
}
}
@Stateless
public class StudentManager extends AcademicManager implements StudentManagerRemote {
@PersistenceContext
private EntityManager em;
...
@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);
}
}
...
}
和em.flush()
。