gpt4 book ai didi

java - JPA CascadeType.REMOVE 不删除关系的子级

转载 作者:太空宇宙 更新时间:2023-11-04 14:12:26 25 4
gpt4 key购买 nike

在我的项目中,我有下面报告的类,并具有双向关系映射。当我尝试删除关系的父对象(在我的例子中为 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);
}

.

最佳答案

感谢 @Smutje 链接,我将查询更改为以下内容(有效):

Iterator itr = itemsToDelete.iterator();
int deleted = 0;
while(itr.hasNext()) {
em.remove(itr.next());
deleted++;
}

不幸的是,批量删除可能不是很快,但至少对于简单的删除查询,它可以正确级联。

关于java - JPA CascadeType.REMOVE 不删除关系的子级,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28151237/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com