简体   繁体   English

使用Spring Boot和Hibernate保护单个实体免于级联删除

[英]Protect a single entity from cascade deletion with Spring Boot and Hibernate

I have a project that I'm working on in which I have a group and that group has a group-image (id and url). 我有一个正在处理的项目,其中有一个组,并且该组有一个组图像(id和url)。 When I delete a particular group, I want it to delete its image entity from the MySql database as well. 当我删除特定的组时,我也希望它也从MySql数据库中删除其图像实体。

But, the first group-image entity in the database is a url to a generic icon that I have placed there with an ID of one. 但是,数据库中的第一个组图像实体是指向我放置在其中的ID为1的通用图标的URL。

I understand that when I delete a group, the associated image entity gets deleted as I have the cascade type set to all. 我了解到,当我删除组时,由于将层叠类型设置为全部,因此关联的图像实体也会被删除。

This presents a problem when a group that uses the generic icon is deleted as it will then set the group_image_id to NULL causing an NPE. 当删除使用通用图标的组时会出现问题,因为它随后会将group_image_id设置为NULL,从而导致NPE。

My question is, is there a way to protect a single group-image entity from the effects of cascade delete? 我的问题是,有没有一种方法可以保护单个组图像实体免受级联删除的影响?

I have never tried this, but one option to explore is customizing the delete statement that is used on the entity type that you want to prevent deletion where id=1. 我从未尝试过此方法,但是要探索的一个选项是自定义要在id = 1时要防止删除的实体类型上使用的delete语句。 You can do this with the @SQLDelete annotation and include in the where-clause "and id <> 1" or something similar. 您可以使用@SQLDelete批注进行此操作,并在其中包括“和id <> 1”或类似内容。

The default behavior (without specifying @SQLDelete) is to delete by ID. 默认行为(不指定@SQLDelete)是按ID删除。

I am suggesting that try something like: 我建议尝试类似的方法:

@Table(name="mytable")
@SQLDelete("delete from mytable where id=? and id<>1")
public class MyEntity {
    ...
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM