JPA + EclipseLink - 以@OneToMany关系移动实体

时间:2014-08-18 14:02:18

标签: jpa one-to-many

我对OneToMany RelationsShip的实现与此描述类似:

http://en.wikibooks.org/wiki/Java_Persistence/OneToMany

实体组:

@Entity
public class Group {

@OneToMany(cascade = { CascadeType.ALL }, orphanRemoval = true)
private List<Unit> units = new ArrayList<Unit>();

 public void addUnit(Unit unit) {
    this.units.add(unit);
    if (unit.getGroup() != this) {
        unit.setGroup(this);
 }
}

实体单位:

@Entity
public class Unit {

@ManyToOne(cascade = CascadeType.PERSIST)
private Group Group;

public void setGroup(Group Group) {
    this.Group = Group;
    if (Group != null && !Group.getGoodItems().contains(this)) {
        Group.getGoodItems().add(this);
    }
 }
}

现在我想在两组之间移动1个单位:

unit.setGroup(组2);

在该操作之后,我可以在数据库中看到关系表GROUP_UNIT 该单位现在与group1和group2相关。

如何正确地在两组之间移动单位?

1 个答案:

答案 0 :(得分:1)

您应该在注释中添加mappedBy:

@OneToMany(cascade = { CascadeType.ALL }, orphanRemoval = true, mappedBy="Group")
private List<Unit> units = new ArrayList<Unit>();

使用mappedBy,您将不再需要JOIN_TABLE。

相关问题