0

Car与 1:n 关系Feature

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

Class 中的表示形式Feature如下所示:

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

当我将Feature与某个Car-Object 关联的一个 -object 传递给DatabaseService#delete()它时,它将成功地从数据库中删除,但仍位于Car-Objects 功能列表中。

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);
    }
}
4

1 回答 1

0

不要在 Feature 上调用数据库操作。在集合上设置级联属性,从 Car 中删除特征,然后持久化 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);
    }
}
于 2013-11-14T13:28:28.377 回答