从列表中删除项目时遇到问题。该列表在父类(super class)中定义,但 Hibernate 注释应用于子类中的属性访问器。父类(super class)中有两种方法可以操作列表。 “添加”方法工作正常,但“删除”方法不会保留更改。我已经检查了我的 Cascade 设置,似乎一切正常。我在做一些不可能的事情吗?如果不是,我做错了什么吗?
这是我的类(class):
@Entity
abstract class Temporal<T> {
@Id
@GeneratedValue
private Long id;
@Version
private Integer version = null;
@Transient
protected List<T> content = new ArrayList<T>();
public void remove(T value) {
// business logic ...
content.remove(value);
}
public void add(T value) {
// business logic ...
content.add(value);
}
}
@Entity
@AccessType("property")
class TemporalAsset extends Temporal<Asset> {
@OneToMany(cascade = CascadeType.ALL, mappedBy = "temporal")
public List<Asset> getContent() {
return super.content;
}
protected void setContent(List<Asset> list) {
super.content = list;
}
}
我按如下方式使用 TemporalAsset 类的一个实例(请注意,我仅使用“刷新”方法来演示该行为。即使我刷新或关闭 session 并打开一个新 session ,该列表也不会正确保留) :
temporalAsset.add(value1);
temporalAsset.getContent().size() == 1; // true
session.update(temporalAsset);
session.refresh(temporalAsset);
temporalAsset.getContent().size() == 1; // true
temporalAsset.remove(value1);
temporalAsset.getContent().size() == 0; // true
session.update(temporalAsset);
session.refresh(temporalAsset);
temporalAsset.getContent().size() == 0; // false, its 1
谢谢。
最佳答案
您必须将级联显式指定为 CascadeType.DELETE_ORPHAN。
尝试将代码更改为
@OneToMany
@Cascade(cascade = {CascadeType.ALL, CascadeType.DELETE_ORPHAN}, mappedBy = "temporal")
部分来自 hibernate docs :
If the child object's lifespan is bounded by the lifespan of the parent object, make the parent a full lifecycle object by specifying CascadeType.ALL and org.hibernate.annotations.CascadeType.DELETE_ORPHAN (please refer to the Hibernate reference guide for the semantics of orphan delete)
关于java - hibernate :从列表中删除项目不会持续存在,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/549961/