连接表记录删除时的参照完整性约束违规

时间:2015-05-13 02:29:40

标签: hibernate jpa spring-data-jpa

我在用户和群组之间有多对多的关系。

@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()
}

我希望能够删除用户或组,并删除任何关联的GroupMembership。但是,当我尝试删除用户或组时,我得到一个:

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]

我使用的是Hibernate 4.3.8和Spring Data JPA 1.7.2。

1 个答案:

答案 0 :(得分:7)

当然,尽管在几个小时内找到答案,但我在发布此问题后的一小时内就找到了答案。

添加特定于Hibernate实现的@OnDelete注释似乎解决了这个问题。显然@OneToMany上的级联属性只会影响EntityManager,并且不会使其进入生成的DDL。

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