微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

java – GORM中的树结构(grails)

我正在尝试在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]
}

插入似乎工作正常,但是当我无法加载具有多个级别和子级别的树时.
我想我错过了关系中的一些东西:
– 树应该引用rootLevel(以及可选的所有子级别)
一个Level应该引用它的父级别,它的子级别和全局父树

你能指出我正确的方向来获得这样的树状结构吗?
谢谢

解决方法:

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

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

至于确保加载所有treenode,您始终可以为父节点和子节点的每个treeNode使用eager / non-lazy抓取.但是,如果你的树形结构非常大,可能会有性能损失……

至于渴望/懒惰的提取.看看这里:Using lazy property fetching in Grails / Gorm

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。

相关推荐