我一直试图删除JPA实体上的反向关系,但这种方法效果不佳。我现在正在尝试的是将ManyToOne属性设置为null,然后使用entityManager的merge方法保存它。 ManyToOne关系用cascade all属性标记,但是在dataBase中不删除外键。我该怎么做?非常感谢。
答案 0 :(得分:1)
使用相关代码更容易找出您的意思。但无论如何我会尝试:
@Entity
public class AEntity {
@GeneratedValue (strategy = GenerationType.SEQUENCE)
@Id int id;
//Having some cascade here doesn't matter for our case
//because we now do not cascade anything, we just set this field to
//null. Cascade=REMOVE is about never meaningful (and never fully
//fully portable) in ManyToOne side:
//just think what happens to other AEntity instances that refer to
//same BEntity.
@ManyToOne
BEntity bEntity;
public void setbEntity(BEntity bEntity) {
this.bEntity = bEntity;
}
}
public class BEntity {
@GeneratedValue(strategy = GenerationType.SEQUENCE)
@Id int id;
}
一开始我们有以下数据:
AEntity(ID = 1,bEntity_id = 2)
BEntity(id = 2)
然后删除a和b之间的连接:
AEntity oldDirty = em.find(AEntity.class, 1);
//modify A somewhere else in code
oldDirty.setbEntity(null);
//and bring changes in:
em.merge(oldDirty);
之后我们有:
AEntity(ID = 1,bEntity_id = NULL)
BEntity(id = 2)
如果BEntity也设置了包含AEntity实体(所以说双向关系),那么你也必须从那里删除A,因为你必须自己关心关系。 OneToMany方面可以从级联中删除。
答案 1 :(得分:0)
检查两端关系的级联类型。例如,如果要在删除主实体时删除所有关联实体,则注释应如下所示:@ManyToOne(cascade={CascadeType.REMOVE})
和反向@OneToMany(cascade={CascadeType.REMOVE})