Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- class Organization {
- String name
- static hasMany = [
- users: Person,
- teams: Team
- ]
- static mapping = {
- users cascade: 'all-delete-orphan'
- }
- }
- class Person {
- String name
- Organization organization
- static belongsTo = [Organization, Team]
- static hasMany = [teams: Team]
- static constraints = {
- }
- def beforeDelete() {
- Team.withNewSession {
- removeFromAllTeams()
- }
- true
- }
- def removeFromAllTeams() {
- Team.where {
- members {
- id == this.id
- }
- }.each { Team team ->
- if (team.members.contains(this)) {
- team.members.remove(this)
- team.save()
- }
- }
- }
- }
- class Team {
- String name
- static hasMany = [members: Person]
- static belongsTo = [organization: Organization]
- static constraints = {
- }
- }
- SQL [n/a]; Referential integrity constraint violation: "FKGHKKY8WMH379RPMFH92T807RY: PUBLIC.TEAM_MEMBERS FOREIGN KEY(PERSON_ID) REFERENCES PUBLIC.PERSON(ID) (1)"; SQL statement:
- delete from person where id=? and version=? [23503-194]; nested exception is org.h2.jdbc.JdbcSQLException: Referential integrity constraint violation: "FKGHKKY8WMH379RPMFH92T807RY: PUBLIC.TEAM_MEMBERS FOREIGN KEY(PERSON_ID) REFERENCES PUBLIC.PERSON(ID) (1)"; SQL statement:
- delete from person where id=? and version=? [23503-194]
- @Unroll
- void "user is removed from team before deletion, runManually = #runManually"() {
- given: 'an existing org'
- Organization.withNewSession {
- def organization = new Organization(name: 'Cyberdyne Systems').save(failOnError: true)
- and: 'a person is added'
- organization.addToUsers(name: 'John Connor').save(failOnError: true)
- organization.save(failOnError: true, flush: true)
- and: 'a new team is added to the org'
- organization.addToTeams(name: 'IT').save(failOnError: true, flush: true)
- and: 'the person is added to the team'
- organization.teams.first().addToMembers(organization.users.first())
- organization.save(failOnError: true, flush: true)
- }
- and: 'the person is deleted'
- def userToDelete = Person.first()
- if (runManually) {
- userToDelete.removeFromAllTeams()
- }
- userToDelete.delete(flush: true)
- expect: 'the team has no users'
- Team.first().members.isEmpty()
- and: 'there are no more users'
- Person.count == 0
- where:
- runManually << [true, false]
- }
Add Comment
Please, Sign In to add comment