GORM Relations without dependent delete

爱⌒轻易说出口 提交于 2019-12-23 13:06:13

问题


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?


回答1:


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
}



回答2:


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'
    }

}


来源:https://stackoverflow.com/questions/19665316/gorm-relations-without-dependent-delete

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!