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.
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
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With