我有四个实体Client,ClientAccount,ClientProductAccount和ClientProduct。客户端包含一组ClientAccounts,而ClientAccount包含一组ClientProductAccount,ClientProductAccount具有对ClientProduct的引用。客户也有一组ClientProducts。我正在做的是删除ClientProduct,所以我要做的是删除具有给定ClientProduct的ClientProductAccount,然后从Client中删除ClientProduct。 经过这个过程,我得到
org.hsqldb.HsqlException:违反完整性约束:外键 没有行动FK_7DMBVW6DMUIW2SFWLAQPS42HQ表:CLIENTPRODUCTACCOUNT
到目前为止,我只删除ClientProductAccount并删除了该实体,结果sql为:
Hibernate:
delete
from
ClientProductAccount
where
id=?
and version=?
另一方面,当我添加任务的下一部分以从客户端实体中删除ClientProduct时,我遇到了违反完整性约束和以下sql命令的异常:
Hibernate:
update
ClientProductAccount
set
version=?,
accountPriority=?
where
id=?
and version=?
Hibernate:
delete
from
ClientProduct
where
id=?
and version=?
型号:
@Entity
public class Client {
...
@OneToMany(fetch = FetchType.LAZY, cascade = CascadeType.ALL, orphanRemoval = true)
@JoinColumn(name = "client_id", nullable = false, updatable = false)
private Set<ClientAccount> accounts = new HashSet<>();
@OneToMany(fetch = FetchType.LAZY, cascade = CascadeType.ALL, orphanRemoval = true)
@JoinColumn(name = "client_id", nullable = false, updatable = false)
private Set<ClientProduct> products = new HashSet<>();
...
}
@Entity
public class ClientAccount {
...
@OneToMany(fetch = FetchType.LAZY, cascade = {CascadeType.ALL}, orphanRemoval = true)
@JoinColumn(name = "clientAccount_id", nullable = false, updatable = false)
Set<ClientProductAccount> productOfAccountSet = new HashSet<>();
...
}
@Entity
public class ClientProductAccount {
@ManyToOne(optional = false, fetch = FetchType.LAZY)
@JoinColumn(name = "clientProduct_id", nullable = false, updatable = false)
ClientProduct product;
...
}
和ClientProduct:
@Entity
public class ClientProduct {
@NotNull
@Enumerated(EnumType.STRING)
@Column(nullable = false, length = CommonColumns.ENUM_LENGTH)
ProductType productType;
...
}
负责删除的代码:
Set<ProductType> toBeDeletedProductsSet = client.getProducts().stream()
.map(ClientProduct::getProductType)
.filter(productType -> !productTypeList.contains(productType))
.collect(toSet());
client.getAccounts().forEach(
clientAccount -> clientAccount.getProductOfAccountSet().removeIf(
clientProductAccount -> toBeDeletedProductsSet.contains(clientProductAccount.getProduct().getProductType())
)
);
client.getProducts()
.removeIf(clientProduct -> !productTypeList.contains(clientProduct.getProductType()));
结果应该是,应删除给定ClientProduct的ClientProductAccount,也应删除Client Entity中的ClientProduct。但我得到以下异常:
由于:org.hsqldb.HsqlException:违反完整性约束: 外键无动作; FK_7DMBVW6DMUIW2SFWLAQPS42HQ表: org.hsqldb.error.Error.error处的CLIENTPRODUCTACCOUNT(来源未知) 在org.hsqldb.StatementDML.performReferentialActions(未知来源) 在org.hsqldb.StatementDML.delete(未知来源)处 org.hsqldb.StatementDML.executeDeleteStatement(来源未知) org.hsqldb.StatementDML.getResult(未知源)位于 org.hsqldb.StatementDMQL.execute(未知来源)位于 org.hsqldb.Session.executeCompiledStatement(未知来源)位于 org.hsqldb.Session.execute(未知来源)...还有63个