@OneToMany删除子项 [英] @OneToMany delete children
问题描述
我有两个这样的实体:
public class Client {
...
@OneToMany(mappedBy = "client", cascade = { CascadeType.DETACH, CascadeType.MERGE, CascadeType.REFRESH, CascadeType.REMOVE },orphanRemoval = true, fetch=FetchType.EAGER)
@Fetch(value = FetchMode.SUBSELECT)
@Cascade({ org.hibernate.annotations.CascadeType.SAVE_UPDATE, org.hibernate.annotations.CascadeType.DELETE_ORPHAN })
private List<CompanyContract> companyContracts;
...
}
CompanyContract:
CompanyContract :
public class CompanyContract {
...
@ManyToOne
@JoinColumn(name = "IDCLIENT")
private Client client;
...
}
我想要删除像这样的公司合同:
And I want to delete a companyContract like this :
client.getCompanyContracts().remove(companyContract)
client = clientService.updateClient(client);
但删除过程没有发生
我做错了什么?
编辑
这是我的updateClient方法在我的DAO中:
This is my updateClient method in my DAO :
@Override
@Transactional
public Client updateClient(Client client) {
return entityManager.merge(client);
}
推荐答案
首先,你不要不需要设置 cascadeTypes
和 @Cascade
。我认为这可能是你问题的根源。
First of all, you don't need set cascadeTypes
and @Cascade
. I think it might be a source of your problems.
您是否覆盖
等于
和 hashCode
在 ContractCompany
中?因为你可能没有从列表中删除所需的对象< ContactCompany>
Did you override
equals
and hashCode
in ContractCompany
? because maybe you are not removing the desired object from List<ContactCompany>
看看这个
@OneToMany(mappedBy = "client", ...)
mappedBy
通知hibernate该客户端是此关系的所有者,因此您需要获取 client
,获取 clientContracts
列表,删除一个(确保从列表中删除),更新客户端和删除对象。
mappedBy
informs hibernate that client is the owner of this relation, so you need to get client
, get a list of clientContracts
, remove one (make sure it's removed from the list), update client and removed object.
以下示例源代码
CompanyContract toBeRemoved = //companyContract which you want to delete
client.getCompanyContracts().remove(toBeRemoved);
toBeRemoved.client = null;
保存两个对象, toBeRemoved
和客户
这篇关于@OneToMany删除子项的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!