Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Referential integrity constraint violation on join table record delete

I have a many-to-many relationship between users and groups.

@Entity
class User {
    @OneToMany(cascade = CascadeType.ALL, mappedBy = 'id.user')
    Set<GroupMembership> memberships
}

@Entity
class Group {
    @OneToMany(cascade = CascadeType.ALL, mappedBy = 'id.group')
    Set<GroupMembership> members
}

@Entity
class GroupMembership {

    @Embeddable
    static class IdKey implements Serializable {

        @ManyToOne
        @JoinColumn(name = 'userId')
        User user

        @ManyToOne
        @JoinColumn(name = 'groupId')
        Group group
    }

    @EmbeddedId
    IdKey id = new IdKey()
}

I want to be able to delete a User or a Group and any associated GroupMemberships be removed. However, when I try to delete a User or a Group, I get a:

org.h2.jdbc.JdbcSQLException: Referential integrity constraint violation: "FK_96K9TDEV9PO6Q3ISOYIJPWAQU: PUBLIC.GROUP_MEMBERSHIPS FOREIGN KEY(GROUP_ID) REFERENCES PUBLIC.GROUP(ID) (1)"; SQL statement:
delete from group where id=? [23503-186]

I am using Hibernate 4.3.8 and Spring Data JPA 1.7.2.

like image 423
Jon Peterson Avatar asked May 13 '15 02:05

Jon Peterson


Video Answer


1 Answers

Of course, despite searching for an answer for hours, I figure it out within an hour of posting this question.

Adding the Hibernate-implementation specific @OnDelete annotation seemed to fix it. Apparently the cascade property on @OneToMany only effects the EntityManager and doesn't make it into the generated DDL.

@Entity
class Group {
    @OneToMany(cascade = CascadeType.ALL, mappedBy = 'id.group')
    @OnDelete(action = OnDeleteAction.CASCADE)
    Set<GroupMembership> members
}
like image 120
Jon Peterson Avatar answered Oct 26 '22 23:10

Jon Peterson