Tree structure in GORM (grails)

I am trying to define a tree structure in GORM. Here is my model:

class Tree {
    String name
    Level rootLevel

    static hasOne = [rootLevel: Level]
    static hasMany = [levels: Level]
    static mappedBy = [levels:"parentTree"]
}

class Level {
    String name
    Tree parentTree
    Level parentLevel
    Set<Level> subLevels

    static belongsTo = [parentTree: Tree]
    static hasMany = [subLevels: Level]
}

The insert seems to work fine, but when I cannot load the Tree with many levels and sublevels. I guess I missed something in the relationship: - The tree should have a link to rootLevel (and, possibly, to all sublevels) - The level should have a link to its parent level, its sublevels and the global parent tree

Could you point me in the right direction to get such a tree structure? Thanks

+3
source share
3 answers

I ended up with this solution (thanks to a friend):

class Tree {
   String name
   Level rootLevel

   static hasMany = [levels: Level]
   static mappedBy = [rootLevel: "parentTree", levels: "owningTree"]

   static constraints = {rootLevel(nullable: true)}
}

and

class Level {
   String name
   Tree parentTree
   Tree owningTree
   Level parentLevel
   Set<Level> subLevels

   static belongsTo = [owningTree: Tree, parentLevel: Level]
   static hasMany = [subLevels: Level]
   static mappedBy = [parentTree: "rootLevel", owningTree: "levels", subLevels: "parentLevel"]

   static constraints = {
       parentTree(nullable: true)
       parentLevel(nullable: true)
   }
}

Tree Level (owningTree parentTree) mappedBy, .

-1

, :)

Class TreeNode {
    String name
    TreeNode parent

    static hasMany = [children: TreeNode]

    //returns the root node, and by extension, the entire tree!
    TreeNode getRootNode(){
       if(parent){
          //if parent is not null then by definition this node is a child node of the tree.
          return parent.getRootNode()
       }else{
          //if parent is null then by definition it is the root node.
          return this
       }
    }

    //you might not need this function, but ill add it as it is common in tree structures
    boolean isLeaf(){
       //determines if this node is a leaf node. a leaf is a node with zero childrens
       return children.isEmpty()
    }
}

, treenodes , / treeNode , . , ...

/ . : Grails/Gorm

+11

The problem is that the levels are filled with the identifier of the parent tree, but when you load the Tree, you get the following error: "For the Level class, several lines were found with the given identifier.

Your problem seems to be that for each tree you have more than one root root. This is an unusual approach. To make it work, you must replace Level rootLevelthe object Treewith Set<Level> roots.

0
source