- 问题
最近在开发web(持久层框架用的是mybatis)时遇到一个小问题 : 需要查询对象列表返回到页面,每一个对象中有一个属性是list,我需要获取这个list中的值显示在页面上。
- 解决方案
使用collection解决,因为在开发中遇到一些小坑,所以在这总结举例,避免以后再犯。
商户pojo
public class MercPojo{
private Long id;
private String mercNum;//商户编号
private String mercName;//商户全称
private List<MercSettlePojo> mercSettleList;//商户结算信息
...
}
商户结算信息pojo
public class MercSettlePojo{
private Long id;
private Long merc_id;//商户的id,对应MercPojo的id
private String settleName;//结算账户名称
...
}
Mapper文件 Merc.xml
<select id="selectListByMercId" resultType="...MercSettlePojo">
<![CDATA[
select
t.id,
t.settle_name as settleName <!-- 注意一定要让别名与pojo中的属性一致 -->
from Settle t
]]>
<where>
merc_id = #{merc_id}
</where>
</select>
<select id="selectMerchantList" parameterType="...MercPojo" resultMap="baseResultMap">
<![CDATA[
select m.id,m.merc_num,m.merc_name
...
from Merchant m
]]>
<where>
<if test="mercNum != null and mercNum != ''"><![CDATA[and m.merc_num LIKE '%'||#{mercNum}||'%']]></if>
<if test="mercName != null and mercName != ''"><![CDATA[and m.merc_name LIKE '%'||#{mercName}||'%']]></if>
...
</where>
</select>
<resultMap id="baseResultMap" type="...MercPojo">
<result column="id" property="id" />
<result column="merc_num" property="mercNum" />
<result column="merc_name" property="mercName" />
...
<!-- 下面这句很重要:作用就是通过selectListByMercId查出list然后映射到属性mercSettleList中。其中,ofType为list的泛型,column为子select的入参(这里是id),select为子查询的mapperId-->
<collection property="mercSettleList" ofType="...MercSettlePojo" column="{merc_id=id}" select="selectListByMercId"/>
</resultMap>
sql执行顺序为:先执行selectMerchantList,然后再执行selectListByMercId。
原文参考:https://blog.youkuaiyun.com/u012415035/article/details/97363965
参考 1:https://blog.youkuaiyun.com/qing_gee/article/details/79214721

本文详细介绍了如何在MyBatis中使用集合属性映射,通过具体示例展示了如何将查询结果映射到Java对象的集合属性上,解决了在查询包含列表属性的对象时的常见问题。
5760

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



