在实际项目开发过程中,存在大量的父子集关系查询。
例如需要查询树形结构,一对多的数据集,递归查询如省市区县镇层级联动等业务时,都可以参考如下的写法,无需在代码中动态遍历赋值,效率高,易用性强。
要查询如图所示的数据,详细的实现方式参考如下:
如果要查询一对一可参照如下案例,基本写法与处理一对多的思路类似:
mybatis的使用技巧5——查询一对一数据(javaType和ofType用法区别)
1.存在如下mapper接口:
List<TreeInfo> getTreeInfoObj(TreeInfo TreeInfo);
2.mapper接口对应的xml写法如下:
<select id="getTreeInfoObj" resultMap="ModulesTreeMap" parameterType="com.test.system.entity.TreeInfo">
select syi.*
from tree_info syi
<where>
syi.del_flag = 0 and syi.status = -1
<if test="parentId != null">
and syi.parent_id = #{parentId}
</if>
</where>
order by syi.level asc
</select>
3.详细的resultMap写法如下,其中需要注意resultMap中的collection属性:
<resultMap id="ModulesTreeMap" type="com.test.system.entity.TreeInfo" autoMapping="true" >
<result property="id" column="id" />
<collection column="id" property="children"
ofType="com.test.system.entity.TreeInfo"
select="getTreeInfoByParentId" autoMapping="true">
</collection>
</resultMap>
详细<collection />标签说明,很重要!!!
- column:子查询的动态参数,也就是需要关联查询的筛选条件,注意看子查询的取值
- property:父级对象的属性名称,也就是ColumnInfo下的属性名称
- ofType:子查询映射的数据类型
- select:子查询的mapper接口id,也就是对应的方法名
- autoMapping:开启自动映射,相当于数据库和属性名称按驼峰名称规则自动映射
4.子查询对应的xml写法:
注意#{id},其中的id须和<collection />标签的column属性一致
<select id="getTreeInfoByParentId" resultType="com.test.system.entity.TreeInfo">
select syichi.*
from tree_info syichi
<where>
syichi.del_info = 0 and syichi.parent_id = #{id}
</where>
order by syichi.level asc
</select>