0

我在删除对象时遇到了奇怪的问题。我正在使用 Play Framework 1.2.5 和 PostgreSQL 版本 9.1。

我有以下两个模型:

1)

@Entity
public class CarCollection extends Model {
    @Required
    public String name;

    @OneToMany(mappedBy = "carCollection")
    public List<Car> cars;
}

2)

@Entity
public class Car extends Model {
    @Required
    public String name;

    @OneToMany(mappedBy = "parent", cascade = CascadeType.ALL)
    public List<Car> copies = new ArrayList<Car>();

    @ManyToOne
    public Car parent;
}

所以,在我的情况下,我可以拥有汽车,但可以复制它们然后我保存,例如,2 号汽车是从 1 号汽车复制的,所以 2 号汽车的父级 = 1 号汽车。但它们位于不同的汽车收藏中,这就是现在重要的事情!

现在我想删除一个包含实体(车号 1)的 CarCollection。但正如我所写,1 号车仍然被 2 号车对象作为父对象引用。现在会发生什么?我希望这个 CarCollection 将与 1 号车一起被删除,而在 2 号车的实体中,父值将为空(已删除参考)。
开箱即用是行不通的!怎么了?两辆车都将被删除。但这不是我期望或想要的。

所以我决定通过覆盖两个 delete() 方法来解决这个问题,如下所示:

@Entity
public class CarCollection extends Model {
    @Override
    public CarCollection delete() {
    //delete cars manually
    for(Car car: this.cars){
        car.delete();
    }
}

@Entity
public class Car extends Model {
    @Override
    public Car delete() {
    //delete parents from copied cars
    for (Car car : this.copies) {
        car.parent = null;
        car.save();
    }
}

但它不起作用。我尝试什么都没关系。即使我在删除内容后“刷新()”我的 CarCollection,也无济于事。

那么,我该如何解决这个问题呢?也许我有一个错误的模型定义或依赖定义?!

4

1 回答 1

1

There is two things involved when you delete some entities :

  • cascade definition define in your database when you create your foreign keys
  • cascade definition in your jpa annotations

In your example, the 'copies' relation have a cascade all annotation. So if car2 is in the 'copies' list of 'car1' it will be deleted transitively.

If you want to break the relation by hand by overriding the delete method, you have to do it in both ways. In your case, you do not remove the child from the copies list when you set parent to null.

于 2012-09-10T05:48:42.720 回答