无法从@OneToMany集合中删除元素

时间:2012-07-02 13:57:18

标签: java hibernate java-ee jpa one-to-many

我有一个实体 Entity1 Entity2 一对多关系,如下所示:

1-实体1:

@Entity
@Table(name = "Entity1", catalog = "mydb")
public class Entity1 implements java.io.Serializable {

  @OneToMany(fetch = FetchType.LAZY, mappedBy = "entity1", cascade = javax.persistence.CascadeType.ALL)
  @OrderBy("id")
  private Set<Entity2> collection = new HashSet<Entity2>(
            0);

}

2- Entity2:(等于和重写哈希码方法)

@Entity
@Table(name = "entity2", catalog = "advertisedb")
public class Entity2 implements java.io.Serializable {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name = "pkid", unique = true, nullable = false)
    @Basic(fetch = FetchType.EAGER)
    private long id;

    @ManyToOne(fetch = FetchType.EAGER)
    @JoinColumn(name = "fk_entity1", nullable = false)
    private Entity1 entity1;

    @ManyToOne(fetch = FetchType.EAGER)
    @JoinColumn(name = "apid", nullable = false)
    private Entity3 entity3;

}

3-以下是我从集合中删除实体的方法:

    entity1Obj.getEntity2().remove(entity2);
    log.debug("size after remove: "+ entity1Obj.getEntity2().size()); // size decreases correctly, so the entity is removed from the collection
    entity1Dao.updateEntity1(entity1);

4- DAO方法:

   public void updateEntity1(Entity1 entity1) {
        getCurrentSession().update(getCurrentSession().merge(entity1));
    }

问题:我在控制台中得到的是应该删除的entity2的select查询,没有删除查询,也没有删除任何内容。

请告知如何解决此问题。

1 个答案:

答案 0 :(得分:4)

我将cascade = CascadeType.ALL替换为orphanRemoval = true,现在工作正常。