在我的项目中,我有下面报告的类,具有双向关系映射。 当我尝试删除关系的父级(在我的情况下是DataProvider)时,主对象被删除,而子项不会被删除。 我还测试了其他几种注释组合,其中没有一种似乎有用(orphanRemoval,@ ElementDependent,optional = false,...)。
通过以下查询完成删除:
Query q = em.createQuery("DELETE FROM DataProvider dp WHERE ... ");
q.executeUpdate();
任何人都可以提出建议吗?
@Entity(name = "DataProvider")
public class DataProviderImpl implements DataProvider {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private int id;
private String name;
// ...
@OneToMany(targetEntity=RestMethodImpl.class, fetch=FetchType.LAZY, mappedBy="dataProvider", cascade={CascadeType.PERSIST,CascadeType.REMOVE})
private List<RestMethod> methods;
public DataProviderImpl() {
super();
this.id = 0;
}
@Override
public int getId() {
return id;
}
@Override
public void setId(int id) {
this.id = id;
}
@Override
public String getName() {
return name;
}
@Override
public void setName(String name) {
this.name = name;
}
@Override
public List<RestMethod> getMethods() {
return methods;
}
@Override
public void setMethods(List<RestMethod> methods) {
this.methods = methods;
}
}
public interface DataProvider {
public int getId();
public void setId(int id);
public String getName();
public void setName(String name);
public List<RestMethod> getMethods();
public void setMethods(List<RestMethod> methods);
}
@Entity(name = "RestMethod")
public class RestMethodImpl implements RestMethod {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private int id;
private String nickname;
// ...
@ManyToOne(targetEntity=DataProviderImpl.class, fetch=FetchType.LAZY)
@JoinColumn(name="dataProviderId")
private DataProvider dataProvider;
public RestMethodImpl() {
super();
this.id = 0;
}
@Override
public int getId() {
return id;
}
@Override
public void setId(int id) {
this.id = id;
}
@Override
public String getNickname() {
return nickname;
}
@Override
public void setNickname(String nickname) {
this.nickname = nickname;
}
@Override
public DataProvider getDataProvider() {
return dataProvider;
}
@Override
public void setDataProvider(DataProvider dataProvider) {
this.dataProvider = dataProvider;
}
}
public interface RestMethod {
public int getId();
public void setId(int id);
public String getNickname();
public void setNickname(String nickname);
public DataProvider getDataProvider();
public void setDataProvider(DataProvider dataProvider);
}
答案 0 :(得分:0)
感谢@Smutje链接我将查询更改为以下(有效):
Iterator itr = itemsToDelete.iterator();
int deleted = 0;
while(itr.hasNext()) {
em.remove(itr.next());
deleted++;
}
不幸的是,批量删除可能不是很快,但至少对于简单的删除查询,它可以正常级联。