使用mapper.xml
<!--使用mapper构建树-->
<resultMap id="treeMap" type="com.bx.project.entity.VO.CheckItemLabel">
<id column="suuid" property="id" />
<result column="parent_id" property="parentId"></result>
<result column="pcname" property="title"></result>
<result column="suuid" property="id"></result>
<!--将主键suuid 作为查询参数传递给getChildren,getChildren根据parent_id=suuid的条件查询子节点 -->
<collection property="children" ofType="com.bx.project.entity.VO.CheckItemLabel" column="suuid"
select="getChildren"></collection>
</resultMap>
<!--查询根节点-->
<select id="queryTree" resultMap="treeMap">
select * from p_check_item where parent_id is null
</select>
<!--查询子节点集合-->
<select id="getChildren" resultMap="treeMap" >
select * from p_check_item where parent_id=#{suuid}
</select>
mapperDao接口
//直接查询根节点
public List<CheckItemLabel> queryTree();
实体类
public class CheckItemLabel {
private String id;
private String title;
private String parentId;
private String url;
private String checked;
private List<CheckItemLabel> children;
public void setParentId(String parentId) {
this.parentId = parentId;
}
public void setUrl(String url) {
this.url = url;
}
public void setChecked(String checked) {
this.checked = checked;
}
public String getParentId() {
return parentId;
}
public String getUrl() {
return url;
}
public String getChecked() {
return checked;
}
public void setChildren(List<CheckItemLabel> children) {
this.children = children;
}
public List<CheckItemLabel> getChildren() {
return children;
}
public void setId(String id) {
this.id = id;
}
public void setTitle(String title) {
this.title = title;
}
public String getId() {
return id;
}
public String getTitle() {
return title;
}
}
/渲染树形菜单
layui.admin.req({
url:查询接口,
traditional: true,
data:{"parentId":"0"},
done:function (res) {
tree.render({
elem: '#checkItem', //绑定元素
showCheckbox:true,
id:'checkItemId',
data:res.data
});
}
})
这篇博客介绍了如何使用MyBatis的mapper.xml文件构建树形数据结构。通过定义resultMap,利用collection和select标签,实现了从数据库查询根节点和子节点,形成树状菜单。在实体类中定义了递归结构,便于数据渲染。在layui前端框架中,通过调用接口获取数据并渲染成树形菜单。
5万+

被折叠的 条评论
为什么被折叠?



