OneToOne relationship with cascade deleting both sides

Greggy :

I have project based on JHipster generator. I have two entities: Pattern and File. One pattern has only one file, and one file can be attached only to one pattern. So I think its typical OneToOne relationship. How to delete other entity when deleting is one side of relationshlip? I mean: When I delete Pattern, I want to delete also File. Also, when I delete File, I want to delete Pattern. I have somethink like this:

public class Pattern implements Serializable {
    @OneToOne(mappedBy = "entityPattern")
    @OnDelete(action = OnDeleteAction.CASCADE)
    @JsonIgnore
    private File file;
}

and

public class File implements Serializable {
    @OneToOne(cascade=CascadeType.REMOVE, orphanRemoval = true)
    @JoinColumn(unique = true)
    private Pattern pattern;
}

But it doesnt work. I have org.springframework.dao.DataIntegrityViolationException exception caused with constraint violations.

user10639668 :

This should work:

public class Pattern implements Serializable {
    @OneToOne(mappedBy = "pattern",cascade = CascadeType.REMOVE)
    @JsonIgnore
    private File file;
}

public class File implements Serializable {
    @OneToOne(cascade=CascadeType.REMOVE, orphanRemoval = true)
    @JoinColumn(unique = true)
    private Pattern pattern;
}

I only used JPA compatible code.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=135262&siteId=1