简体   繁体   English

删除一对一关系中的 jpa 实体

[英]Deleting jpa entity on One-To-One relationship

I have two tables that are related to one-to-one relationship:我有两个与一对一关系相关的表:

public class Person {

  // some other fields

  @OneToOne(fetch = FetchType.LAZY, cascade = CascadeType.ALL)
  @JoinColumn(name = "image_id")
  private FileInfoModel image;

}

public class FileInfoModel {

  @Id
  @GeneratedValue(strategy = GenerationType.IDENTITY)
  private Long id;

  @NotBlank
  private String name;

  @NotNull
  @Column(name = "size_in_bytes")
  private Long size;

  // some other fields

}

When I tried to delete the image with the repository: repository.deleteById(file.getId());当我尝试使用存储库删除图像时: repository.deleteById(file.getId()); I get the following error:我收到以下错误:

update or delete on table "file_info" violates foreign key constraint "fk_image" on table "person".表“file_info”上的更新或删除违反表“person”上的外键约束“fk_image”。

Is there any way to set the Person table image_id field to null when deleting FileInfo from the repository?从存储库中删除 FileInfo 时,有什么方法可以将 Person 表 image_id 字段设置为 null? I know I can set person.setImage(null) and save it and then delete the file but I think there could be an easier way with fewer steps.我知道我可以设置 person.setImage(null) 并保存它然后删除文件,但我认为可能有一种更简单的方法,步骤更少。

You could use an JPQL query to automatically set all Persons with that image to a null image before deleting it.您可以使用 JPQL 查询在删除图像之前自动将具有该图像的所有人员设置为空图像。 Roughly:大致:

update Person p set p.image = null where p.image = :image

I'd recommend to be explicit about this and not implement some magic via listeners or similar as you'd generally not expect something to be deleted when references to it still exist.我建议对此进行明确,而不是通过侦听器或类似方法实现一些魔法,因为当对它的引用仍然存在时,您通常不希望删除某些内容。

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

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