java - JPA:删除时违反约束

标签 java jpa

我有三个实体-

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 包含到 ApplicationEntitycategory 字段中。

编辑:

JPA 文档说:

REMOVE – If the owning entity is removed, the target of the association is also removed.

这意味着当您删除 ApplicationEntity 时, CategoryEntity 不会被删除。只会删除它们之间的关联。

编辑:

您应该将CascadeType.REMOVE 添加到ApplicationEntitybuyers 字段。 ApplicationEntity 和 UserEntity 之间存在关系表,当您尝试删除 ApplicationEntity 时,应先删除该关系表中所有引用已删除 ApplicationEntity 的元组。

关于java - JPA:删除时违反约束,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5936260/

相关文章:

java - 为什么 spring data jpa hibernate mariadb 时间戳小数秒在插入时被截断?

java - Confluence 中的 WikiToXhtmlMigrator

java - Install4j - 将 "Next"按钮的文本更改为 "Install"

java - 将java服务器移植到Android

java - 从现有子集创建子集的有效方法?

java - Weblogic 错误 : Caused by: weblogic. transaction.internal.AppSetRollbackOnlyException:在事务上调用 setRollbackOnly

java - 为什么我们需要双向同步方法?

hibernate - JPA 计数查询以按查询计算组的总结果行

java - 如何连接 - 断开连接 - 重新连接到 Neo4j 服务器实例

java - 查询没有实体类的数据库表