有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

GORM(grails)中的java树结构

我试图在GORM中定义一个树结构。这是我的模型:

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

插入似乎很好,但当我无法加载一棵包含许多级别和子级别的树时。 我想我错过了关系中的一些东西: -树应该有一个对根级别(以及可选的所有子级别)的引用 -一个级别应该有一个对其父级、子级和全局父树的引用

你能给我指出一个正确的方向来建造这样的树结构吗? 谢谢


共 (2) 个答案

  1. # 1 楼答案

    我最终得到了这个解决方案(感谢一位朋友):

    class Tree {
       String name
       Level rootLevel
    
       static hasMany = [levels: Level]
       static mappedBy = [rootLevel: "parentTree", levels: "owningTree"]
    
       static constraints = {rootLevel(nullable: true)}
    }
    

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

    我忽略了树和级别(owningTree和parentTree)之间的两种关系,以及一些帮助休眠的mappedBy配置

  2. # 2 楼答案

    我不喜欢你的树结构,所以我创建了自己的:)

    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()
        }
    }
    

    至于确保加载所有树节点,您始终可以对每个树节点(包括父节点和子节点)使用即时/非延迟抓取。但是,如果你的树结构非常大,可能会有性能损失

    至于急切/懒惰的抓取。看看这里:Using lazy property fetching in Grails / Gorm