Mybatis Plus 查询嵌套子列表 两种方式:集中查询;分布查询。
要得到类似结果结构如下:
Array(2)
0: {
id: '',
list: Array(8)
0: {…}
1: {…}
2: {…}
3: {…}
4: {…}
5: {…}
6: {…}
7: {…}
}
1: {…}
// 主表查询dao.java
List<dto> selectAll(@Param(Constants.WRAPPER)QueryWrapper<Entity> wrapper);
//子表查询dao.java
List<dto> getList(@Param(@Param("id" Long id));
<!-- 主表dao.xml-->
<resultMap type="com.*.dto.AllDTO" id="AllMap">
<result property="id" column="id"/>
<collection property="list" ofType="com.*.Entity"
select="dao.getList" column="id"><!-- 主表colum的id 传递给子表查询-->
</collection>
</resultMap>
<select id="selectAll" resultMap="AllMap">
select * from demo ${ew.customSqlSegment}
</select>
<!-- 子表dao.xml-->
<select id="getList" resultType="com.*.Entity">
select * from other where demo_id=#{id} order by id asc
</select>
推荐方式一。可避免两个表中字段名重复,导致QueryWrapper的查询参数配置找不到column。对子表有更复杂的查询操作时,会更灵活,比如说排序等。
// 主表查询dao.java
List<dto> selectAll(@Param(Constants.WRAPPER)QueryWrapper<Entity> wrapper);
<!-- 主表dao.xml-->
<resultMap type="com.*.AllDTO" id="AllMap">
<result property="id" column="id"/>
<result property="arrange" column="arrange"/>
<collection property="list" ofType="com.*.DTO">
<result column="id" property="id" />
<result column="name" property="name" />
<result column="type" property="type" />
</collection>
</resultMap>
<select id="selectAll" resultMap="AllMap">
select demo.*,other.id,other.name,other,type
from demo left join other on demo.id = other.demo_id
${ew.customSqlSegment}
</select>
er on demo.id = other.demo_id
${ew.customSqlSegment}
> 两种方式各有利弊,在此纪录一下!