【发布时间】:2020-08-12 23:22:21
【问题描述】:
由于某种原因,当我尝试删除其中包含 elementcollection 的父元素时,我的 delete 没有级联,这两个类如下:
@Entity
@Table(name="Timestamps")
@JsonIgnoreProperties(ignoreUnknown = true)
public class ProductList {
private boolean success;
@Id
private Date lastUpdated;
private String time = "minute";
@ElementCollection
@MapKeyColumn(name="product_id")
@CollectionTable(name="Products")
private Map<String,Product> products;
还有:
@Embeddable
@JsonIgnoreProperties(ignoreUnknown = true)
public class Product{
@Embedded
private Status quick_status;
目前这是我在班级中唯一的字段,因为我已经删除了所有其他字段,试图弄清楚为什么当我尝试删除父对象时删除不会级联到 Products 表。以下是我正在运行的查询:
DELETE FROM Timestamps list WHERE list.last_updated !=0;
last_updated 值总是非零,所以我只是使用这个查询来测试删除,但即使我在 mysql shell 中运行查询,我也会得到“无法删除或更新父行:外键约束失败”我认为 elementcollection 注释应该是自动级联的,有什么我遗漏的吗?
编辑,当下面是 Hibernate 发送的 sql 命令时,你会注意到第三个它缺少级联。
Hibernate: create table products (product_list_last_updated datetime(6) not null, buy_price float not null, sell_price float not null, product_id varchar(255) not null, primary key (product_list_last_updated, product_id)) engine=InnoDB
Hibernate: create table timestamps (last_updated datetime(6) not null, success bit not null, time varchar(255), primary key (last_updated)) engine=InnoDB
Hibernate: alter table products add constraint FKo31ur4gpvx1d5720rgs3qaawi foreign key (product_list_last_updated) references timestamps (last_updated)
编辑 2:下面是 ProductListRepository 类的@Query,我包含在与删除相关的查询中。
@Repository
public interface ProductListRepository extends CrudRepository<ProductList, Integer>{
@Modifying
@Query(value = "DELETE FROM Timestamps list WHERE list.last_updated !=0", nativeQuery = true)
void deleteOld();
}
【问题讨论】:
-
您如何发布删除声明:
DELETE FROM Timesta...?直接在您的 SQL 编辑器中?或者,在@Query?或者是其他东西?如果您尝试使用对应的产品存储库删除它会发生什么情况:例如:productRepository.delete(productsToBeDeleted)? -
@Rafa 好吧,我已经尝试了这两种方法,最终目标是让它与 Query 注释一起运行,但我一直在使用 MySQL shell 对其进行测试,因为如果我可以让它工作那么在存储库类中使用它应该没问题。我也试过 productRepository.deleteAll();它确实级联了删除,但是为什么它可以工作,但指定使用 Query 注释并将其直接输入 MySQL shell 不起作用?
-
@IDKWhatImDoing ,您想要实现的方式似乎很疯狂。为什么要在删除日志时删除产品???如果在删除产品时删除日志,我会更有意义。没有感觉仍然存储已删除产品的日志。
标签: mysql spring spring-boot cascade cascading-deletes