在Spring Boot中使用deleteById与一对多关系生成的查询尝试将引用实体中的外键设置为null,而不是删除它们。我正在使用默认存储库deleteById我已在实体中的外键定义中将 Cascadetype 设置为 ALL,将 OrpahnRemoval 设置为 true,并在创建表的 DDL 中设置 ON DELETE CASCADE。这里是controller类中的删除操作@Transactional@DeleteMapping("transferImage/{imageId}")public void deleteTransferImage(@PathVariable int imageId) { repository.deleteById(imageId);}这是从父实体到子实体的引用@OneToMany(cascade = CascadeType.ALL, fetch = FetchType.EAGER, OrphanRemoval = true)@JoinColumn(name = "TRANSFER_IMAGE_ID")private List<TransferPartition> partitions = new ArrayList<>();这是子实体中外键的定义@JsonIgnore@ManyToOne@JoinColumn(name = "TRANSFER_IMAGE_ID", referencedColumnName = "TRANSFER_IMAGE_ID")private TransferImage image;这是用于创建两个表的 DDLCREATE TABLE TRANSFER_IMAGE (TRANSFER_IMAGE_ID SERIAL CONSTRAINT TRANSFER_IMAGE_PK PRIMARY KEY,IMAGE_NAME VARCHAR(50) CONSTRAINT TRANSFER_IMAGE_NAME_UK UNIQUE NOT NULL ,REQUESTED_PART_SIZE_MB INTEGER NOT NULL,SIZE_BYTES INTEGER NOT NULL,IMAGE_MD5_HASH VARCHAR(100),NUMBER_PARTITIONS INTEGER,DELETED BOOLEAN NOT NULL);CREATE TABLE TRANSFER_PARTITION (TRANSFER_PARTITION_ID SERIAL CONSTRAINT TRANSFER_PARTITION_PK PRIMARY KEY,TRANSFER_IMAGE_ID INTEGER NOT NULL CONSTRAINT TRANSFER_PARTITION_IMAGE_FK REFERENCES TRANSFER_IMAGE ON DELETE CASCADE ON UPDATE CASCADE,PARTITION_NUMBER INTEGER NOT NULL,PARTITION_MD5_HASH VARCHAR(100) NOT NULL,SIZE_BYTES INTEGER NOT NULL);
1 回答
qq_遁去的一_1
TA贡献1725条经验 获得超7个赞
您的问题在于 TransferImage 类中外键关系的定义。
代替
@OneToMany(cascade = CascadeType.ALL, fetch = FetchType.EAGER, OrphanRemoval = true)
@JoinColumn(name = "TRANSFER_IMAGE_ID")
private List<TransferPartition> partitions = new ArrayList<>();
你应该使用
@OneToMany(mappedBy="image", cascade = CascadeType.ALL, fetch = FetchType.EAGER, OrphanRemoval = true)
private List<TransferPartition> partitions = new ArrayList<>();
添加回答
举报
0/150
提交
取消