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