[英]Hibernate/JPA - Delete table with @OneToMany relationship (one parent- 0 or more child of the same type) violates foreign key constraint
I have a problem when trying to delete a table with @OneToMany relationship to table created 尝试删除与创建的表具有@OneToMany关系的表时出现问题
from the same java class using 从同一java类使用
Query q = getEntityManager().createQuery("DELETE FROM " + entityClass.getSimpleName());
q.executeUpdate();
Here's the table: 这是桌子:
CREATE TABLE p_data_group
(
data_group_id bigint NOT NULL,
description character varying(350),
description_eng character varying(350),
multiplicity_max integer,
multiplicity_min integer,
name character varying(35),
name_db character varying(30),
name_eng character varying(35),
name_xml character varying(35),
path character varying(1024),
"position" integer,
is_root boolean,
parent_group_id bigint,
CONSTRAINT p_data_group_pkey PRIMARY KEY (data_group_id ),
CONSTRAINT fk_data_group_parent_group_id FOREIGN KEY (parent_group_id)
REFERENCES p_data_group (data_group_id) MATCH SIMPLE
ON UPDATE NO ACTION ON DELETE NO ACTION
)
WITH (
OIDS=FALSE
);
ALTER TABLE p_data_group
OWNER TO postgres;
And here's the part of the class that represents relations: 这是类中代表关系的部分:
@ManyToOne
@JoinColumn(name = "parent_group_id", insertable = false, updatable = false)
@XmlTransient
public DataGroup getParentDataGroup() {
return parentDataGroup;
}
@OneToMany(cascade = CascadeType.ALL, orphanRemoval = true)
@JoinColumn(name = "parent_group_id")
@ForeignKey(name = "fk_data_group_parent_group_id")
@Index(name = "idx_data_group_parent_group_id")
@LazyCollection(LazyCollectionOption.FALSE)
@XmlElementWrapper
public List<DataGroup> getChildDataGroups() {
return childDataGroups;
}
Now when trying to delete to root table all others should be deleted as well according to CascadeStyle.ALL annotation : 现在,当尝试删除到根表时,也应根据CascadeStyle.ALL注释删除所有其他表:
PSQLException: ERROR: update or delete on table "cpdm01" violates foreign key constraint "fk_cpdm01_kodpkd_cpdm01_id" on table "cpdm01_kodpkd" Detail: Key (cpdm01_id)=(100) is still referenced from table "cpdm01_kodpkd". PSQLException:错误:对表“ cpdm01”进行更新或删除违反了表“ cpdm01_kodpkd”上的外键约束“ fk_cpdm01_kodpkd_cpdm01_id”详细信息:密钥(cpdm01_id)=(100)仍从表“ cpdm01_kodpkd”中引用。
Am I right here? 我在这里吗?
As per your Error log shows 根据您的错误日志显示
DETAIL: Key (cpdm01_id)=(100) is still referenced from table "cpdm01_kodpkd".
There is still a record referencing to cpdm01_id 100. You might delete record in cpdm01_kodpkd with cpdm01_id = 100 before , but there might be others as well. 仍然有一条引用cpdm01_id 100的记录。您可以删除cpdm01_id = 100之前的cpdm01_kodpkd中的记录,但也可能有其他记录。 You have to delete all records in cpdm01_kodpkd referencing to cpdm01_id 100 in main_order. 您必须删除在maindorder中引用cpdm01_id 100的cpdm01_kodpkd中的所有记录。 If not, the database protects you from doing harm to your data. 如果没有,数据库将保护您免受对数据的伤害。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.