Question

I have two domain classes User and Node. The following conditions should hold.

  • a User can have zero or one node
  • a Node can have one to n User (it is always initialized with a User instance)
  • if you delete a Node the User will not be deleted
  • if you delete a User the reference in the Node will be deleted

I tried:

class User {
   Node node
}

class Node {

  // constructor
  Node(User user) {
    addToUsers(user)
    save()
  }  

  hasMany = [users: User]
}

The former does not work. It does not work because when you delete a node there is a dependent reference in the user instance that will not be delete automatically.

How can I model the domain classes in this case?

Was it helpful?

Solution

Use a join table like this:

class User {
    Set<Node> getNodes() {
        UserNode.executeQuery("select x.node from UserNode x where x.user = :user", [user: this])
    }

    def addToNodes(Node node) {
       def userNode = new UserNode()
       userNode.user = this
       userNode.node = node
       userNode.save()      
    }
}


class Node {
      Set<User> getUsers() { ... }
}

class UserNode {
   User user
   Node node
}

OTHER TIPS

Mark node as nullable and add a cascade mapping to the User class, specifying what operations you want to be cascaded:

class User {
    Node node

    static constraints = {
        node nullable: true
    }

    static mapping = {
        node cascade: 'save-update,delete'
    }

}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top