通过mybatis查询树状结构的数据,超级实用。
1,定义实体类
public class Menu {
private String id; //主键
private String pid; //父级主键
private String name; //菜单名称
private List<Menu> children; //子菜单集合
}
2,写mapper.xml
<!-- 映射结果 -->
<resultMap id="treeMap" type="com.hhy.menu">
<id column="id" property="id" />
<result column="pid" property="pid" />
<result column="name" property="name" />
<collection property="children" column="id" ofType="com.mde.template.vo.Menu" select="selectChild"/>
</resultMap>
<!-- 查询父节点 -->
<select id="selectMenuTree" resultMap="treeMap" >
SELECT * FROM menu WHERE pid ='' OR pid is NULL OR pid = 'ROOT' OR pid = 'root' ORDER BY `create_time` ASC
</select>
<!-- 查询子节点 -->
<select id="selectChild" parameterType="java.lang.String" resultMap="treeMap" >
SELECT * FROM menu WHERE pid = #{arg0}
</select>