删除关联对象后如何同步刷新关系?

时间:2013-11-14 12:49:32

标签: java-ee jpa

班级CarFeature的关系为1:n:

@OneToMany(mappedBy="car", fetch = FetchType.EAGER)
private List<Feature> features;

班级Feature中的表示如下所示:

@ManyToOne(fetch = FetchType.EAGER)
private Car car;

当我将一个Feature - 与某个Car - 对象相关联的对象传递给DatabaseService#delete()时,它将成功从数据库中删除,但仍然在Car - 对象中功能列表。

package mypackage;

import java.io.Serializable;

import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;

@Stateless
public class DatabaseService implements Serializable {

    @PersistenceContext
    private EntityManager em;

    public void delete(Object o) {
        o = em.merge(o);
        em.remove(o);
    }
}

1 个答案:

答案 0 :(得分:0)

不要在Feature上调用数据库操作。在集合上设置级联属性,从Car中删除该功能,然后保留汽车。然后内存模型和数据库同步。

public class Car {
    @OneToMany(mappedBy = "car", fetch = FetchType.EAGER, cascade = CascadeType.ALL, orphanRemoval = true)
    private List<Feature> features;

    public void removeFeature(Feature feature) {
        features.remove(feature);
        feature.setCar(null);
    }

    public void addFeature(Feature feature){
        features.add(feature);
        feature.setCar(this);
    }
}