更新具有多对多关系的实体

时间:2012-01-05 22:29:48

标签: java-ee persistence many-to-many ejb-3.0

我有这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()?

1 个答案:

答案 0 :(得分:1)

当您致电group.getMembers()时,您只是从Set实体获得了包含Student的{​​{1}}的副本。因此,当您更新它时,Group实体内的Set不会更新。你有两个选择:

  1. Group获取Set并在更新后退回:

    Group
  2. Set<Student> members = group.getMembers(); members.add(student); group.setMembers(members); 实体&amp;内部添加方法addStudent要在Group方法中调用的addGroup实体中的方法Student。它会是这样的:

    requestAnswer
  3. 此外,您实际上不需要致电@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()