0

I have a Category Entity which can be set to some CredentialData Entity. They are connected with a OneToMany relationship.

I want to be able to delete Categories even when they are used in CredentialData. When I set the Categories CascadeType to ALL/ REMOVE or orphanRemoval than the CredentialData will also be deleted what I dont want to happen. I just want the Category in CredentialData to be set to null when it got deleted. Is there a way to fix this?

CredentialEntity:

@Entity
@Getter
@Setter
@NoArgsConstructor
@AllArgsConstructor
public class CredentialData extends BaseEntity {

    @ManyToOne
    @JoinColumn(name = "categoryId")
    private Category category;

    @ManyToOne
    @NotNull
    @JoinColumn(name = "ownerId", nullable = false)
    private User owner;

CategoryEntity:

@Entity
@Getter
@Setter
@NoArgsConstructor
@AllArgsConstructor
public class Category extends BaseEntity {

    @ManyToOne
    @NotNull
    @JoinColumn(name = "ownerId", nullable = false)
    private User owner;

    @JsonIgnore
    @OneToMany(mappedBy = "category", cascade = CascadeType.PERSIST)
    private Set<CredentialData> credentialData;
jarlh
  • 42,561
  • 8
  • 45
  • 63
Chimitsu Nagase
  • 167
  • 1
  • 9
  • You can not delete parent table column which associate with child table column. first delete child table column after that delete parent table column – Faheem azaz Bhanej Feb 16 '22 at 11:58
  • Ok thank you. Then I have to manually set it to null in the service. – Chimitsu Nagase Feb 16 '22 at 13:04
  • No this is bad option... – Faheem azaz Bhanej Feb 16 '22 at 13:13
  • Can you explain why? Because I want to be able to delete the categories without being forced to delete all CredentialData first. But I also want to keep CredentialData with 'null'-category in case a category gets deleted and was already in use. – Chimitsu Nagase Feb 16 '22 at 13:27
  • see here https://stackoverflow.com/questions/29609400/why-sql-cannot-delete-parent-row-when-references-are-deleted#:~:text=The%20reason%20why%20you%20can,primary%20keys%20in%20parent%20tables. – Faheem azaz Bhanej Feb 16 '22 at 13:31
  • ON DELETE SET NULL -> is what I am searching for. is there no way in doing this in spring boot? – Chimitsu Nagase Feb 16 '22 at 13:37
  • https://stackoverflow.com/questions/9944137/have-jpa-hibernate-to-replicate-the-on-delete-set-null-functionality Is what I was searching for. Thank you for your help @FaeemazazBhanej – Chimitsu Nagase Feb 16 '22 at 14:05

0 Answers0