简体   繁体   中英

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()); I get the following error:

update or delete on table "file_info" violates foreign key constraint "fk_image" on table "person".

Is there any way to set the Person table image_id field to null when deleting FileInfo from the repository? 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.

You could use an JPQL query to automatically set all Persons with that image to a null image before deleting it. 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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