跳到主要内容

3.2 控制节点是否递归

查询动态实体

TreeNodeTable table = TreeNodeTable.$;

List<TreeNode> rootNodes = sqlClient
.createQuery(table)
.where(table.parentId().isNull())
.select(
table.fetch(
TreeNodeFetcher.$
.allScalarFields()
.recursiveChildNodes(cfg -> {
cfg.recursive(it -> {
return !it.getEntity().name().equals("Clothing");
});
})
)
)
.execute();

如果当前树节点的名称等于Clothing则终止递归,否则继续递归。得到如下结果

[
{
"id":1,
"name":"Home",
"childNodes":[
{
"id":2,
"name":"Food",
"childNodes":[
{
"id":3,
"name":"Drinks",
"childNodes":[
{
"id":4,
"name":"Coca Cola",
"childNodes":[]
},
{
"id":5,
"name":"Fanta",
"childNodes":[]
}
]
},
{
"id":6,
"name":"Bread",
"childNodes":[
{
"id":7,
"name":"Baguette",
"childNodes":[]
},
{
"id":8,
"name":"Ciabatta",
"childNodes":[]
}
]
}
]
},
{"id":9,"name":"Clothing"}
]
}
]
信息

Clothing对象并非表现为childNodes属性为[],而是根本没有childNodes属性。

这表示,Clothing对象是否有下级对象是未知的,因为递归过程因人为干预而被提前终止。

查询静态DTO

创建ChildNodesPropFilter类,实现org.babyfish.jimmer.sql.fetcher.RecursionStrategy<E>接口

ChildNodesRecursionStrategy.java
package com.yourcompany.yourpackage.strategy;

...省略import语句...

public class ChildNodesRecursionStrategy implements RecursionStrategy<TreeNode> {

@Override
public boolean isRecursive(Args<TreeNode> args) {
return !args.getEntity().name().equals("Clothing");
}
}

src/main/dto文件夹下新建任何一个扩展名为dto的文件,编辑代码如下

export com.yourcompany.yourproject.model.TreeNode
-> package com.yourcompany.yourproject.model.dto

import com.yourcompany.yourpackage.strategy.ChildNodesRecursionStrategy

RecursiveTreeNodeView {
#allScalars(this)

!recursion(ChildNodesRecursionStrategy)
childNodes*
}

编译项目,生成Java/Kotlin类型RecursiveTreeNodeView

TreeNodeTable table = TreeNodeTable.$;

List<RecursiveTreeNodeView> rootNodes = sqlClient
.createQuery(table)
.where(table.parentId().isNull())
.select(
table.fetch(RecursiveTreeNodeView.class)
)
.execute();

得到如下结果

[
RecursiveTreeNodeView(
id=1,
name=Home,
childNodes=[
RecursiveTreeNodeView(
id=9,
name=Clothing,
childNodes=null
),
RecursiveTreeNodeView(
id=2,
name=Food,
childNodes=[
RecursiveTreeNodeView(
id=6,
name=Bread,
childNodes=[
RecursiveTreeNodeView(
id=7,
name=Baguette,
childNodes=[]
),
RecursiveTreeNodeView(
id=8,
name=Ciabatta,
childNodes=[]
)
]
),
RecursiveTreeNodeView(
id=3,
name=Drinks,
childNodes=[
RecursiveTreeNodeView(
id=4,
name=Coca Cola,
childNodes=[]
),
RecursiveTreeNodeView(
id=5,
name=Fanta,
childNodes=[]
)
]
)
]
)
]
)
]