我有三个实体-
public class ApplicationEntity extends ModelEntity implements Application {
@ManyToOne(fetch = FetchType.LAZY, optional = false, cascade = {CascadeType.MERGE, CascadeType.PERSIST, CascadeType.REFRESH})
private CategoryEntity category;
@ManyToMany(fetch = FetchType.LAZY, cascade = {CascadeType.MERGE, CascadeType.PERSIST, CascadeType.REFRESH})
@JoinTable(
joinColumns = {@JoinColumn(name = "APPLICATION_ID")},
inverseJoinColumns = {@JoinColumn(name = "USER_ID")},
uniqueConstraints = {@UniqueConstraint(columnNames = {"APPLICATION_ID", "USER_ID"})
})
private List<UserEntity> buyers = new ArrayList<UserEntity>();}
public class CategoryEntity extends ModelEntity implements Category {
@Column(nullable = false)
private String name;
@OneToMany(fetch = FetchType.LAZY, cascade = CascadeType.ALL)
private List<ApplicationEntity> applications = new ArrayList<ApplicationEntity>();
}
public class UserEntity extends AbstractEntity implements User {
}
当我尝试删除 AppliationEntity 时,我遇到了违反约束的异常。我试图从 CategoryEntity 中删除应用程序条目,然后删除 ApplicationEntity。但仍然失败。异常类似于 --
Caused by: java.sql.SQLException: DELETE on table 'APPLICATIONENTITY' caused a violation of foreign key constraint 'FK109DF15D362F642' for key (32779). The statement has been rolled back.
at org.apache.derby.impl.jdbc.SQLExceptionFactory.getSQLException(Unknown Source)
at org.apache.derby.impl.jdbc.SQLExceptionFactory40.wrapArgsForTransportAcrossDRDA(Unknown Source)
... 61 more
Caused by: ERROR 23503: DELETE on table 'APPLICATIONENTITY' caused a violation of foreign key constraint 'FK109DF15D362F642' for key (32779). The statement has been rolled back.
非常感谢任何建议。提前致谢。
最佳答案
CategoryEntity 引用了 ApplicationEntity,这就是当您尝试删除引用的 ApplicationEntity 实例时出现约束违反异常的原因。
您应该将 CascadeType.REMOVE
包含到 ApplicationEntity
的 category
字段中。
编辑:
JPA 文档说:
REMOVE – If the owning entity is removed, the target of the association is also removed.
这意味着当您删除 ApplicationEntity 时, CategoryEntity 不会被删除。只会删除它们之间的关联。
编辑:
您应该将CascadeType.REMOVE
添加到ApplicationEntity
的buyers
字段。 ApplicationEntity 和 UserEntity 之间存在关系表,当您尝试删除 ApplicationEntity 时,应先删除该关系表中所有引用已删除 ApplicationEntity 的元组。
关于java - JPA:删除时违反约束,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5936260/