Spring jpa can't delete entity because a table has fk to it

Viewed 63
@Entity
@Getter
@Setter
@Table(name = "children")
public class Child extends BaseEntity {

    @Column(name = "firstName")
    private String firstName;

    @Column(name = "lastName")
    private String lastName;

    @OneToOne
    @JoinColumn(name = "group_id", referencedColumnName = "id")
    private Group group;

    @Column(name = "medical_info")
    private String medicalInfo;

    @Column(name = "birth_date")
    @Temporal(TemporalType.DATE)
    private Date birthDate;

    @Column(name = "starting_date")
    @Temporal(TemporalType.DATE)
    private Date startingDate;

    @Column(name = "native_language")
    private String nativeLanguage;

    @Column(name = "second_language")
    private String secondLanguage;

    private String picture;
}

I try to delete a group but this fail because some Child has fk to that group. The group does not have any fk to Child. I can do it by finding all children with fk to that group and set the group to null then save but this looks hacky and for sure there is a better option. How I can remove that fk in a good way?

1 Answers

If you want set null value at parent you can use CASCADE annotation at you field. You can find more detail in spec: https://docs.oracle.com/cd/E19798-01/821-1841/bnbqm/index.html

An other case if you want delete related entities also you can try orphanRemoval attribute with annotation on related field. Quoting the relevant part from the JPA 2.0 Spec:

Associations that are specified as OneToOne or OneToMany support use of the orphanRemoval option. The following behaviors apply when orphanRemoval is in effect:

If an entity that is the target of the relationship is removed from the relationship (by setting the relationship to null or removing the entity from the relationship collection), the remove operation will be applied to the entity being orphaned. The remove operation is applied at the time of the flush operation. The orphanRemoval functionality is intended for entities that are privately "owned" by their parent entity. Portable applications must otherwise not depend upon a specific order of removal, and must not reassign an entity that has been orphaned to another relationship or otherwise attempt to persist it. If the entity being orphaned is a detached, new, or removed entity, the semantics of orphanRemoval do not apply.

If the remove operation is applied to a managed source entity, the remove operation will be cascaded to the relationship target in accordance with the rules of section 3.2.3, (and hence it is not necessary to specify cascade=REMOVE for the relationship

Orphan removal spec: https://docs.oracle.com/cd/E19798-01/821-1841/giqxy/

Related