设计数据库时
书籍类目储存格式
id name parent_id
1 机电的书 0
2 机械一班的书 1
3 机械一班2012年的书 2
4 机械二班 1
简化名称后
id name parent_id
1 机电的书 0
2 机械一班 1
3 2012年 2
4 机械二班 1
要求 读取机电的书类目 可以获取所有子类目
即读取 机电的书 可以得到 结构
机电的书[
机械一班[
2012年
]
机械二班[]
]
读取 机械一班 可以得到
机械一班[
2012年
]
Mapper层
<resultMap id="BookTypeResultMap" type="com.wxpro.wxproject.bean.BookTypeBean">
<result column="id" property="id" jdbcType="INTEGER" />
<result column="name" property="name" jdbcType="VARCHAR" />
<result column="parent_id" property="parent_id" jdbcType="INTEGER" />
<collection column="id"
property="children"
javaType="java.util.List"
ofType="com.wxpro.wxproject.bean.BookTypeBean"
select="getChildrenById"/>
</resultMap>
<select id="getType" parameterType="int" resultMap="BookTypeResultMap">
SELECT * FROM typeinfo WHERE id = #{typeId}
</select>
<select id="getChildrenById" parameterType="int" resultMap="BookTypeResultMap">
SELECT * FROM typeinfo WHERE parent_id = #{id}
</select>
<select id="getAllType" resultMap="BookTypeResultMap">
SELECT * FROM typeinfo
</select>
resultMap 是 返回值的类型定义,其中collection返回children即子类目的
collection会调用select="getChildrenById"
这里面的方法即
<select id="getChildrenById" parameterType="int" resultMap="BookTypeResultMap">
SELECT * FROM typeinfo WHERE parent_id = #{id}
</select>
**参考资料
https://blog.csdn.net/FANTASY522272820/article/details/70053449**