首页 > 技术文章 > mybatis 查询返回参数包含list的映射写法

yunian139 2019-11-19 14:46 原文

实体类

@Data
public class ListImageTextVO {
    private String id;
    private Integer itype;
    private String title;private List<String> picUrls;  //list集合

}

xml文件(必须写resultMap)

这里列举两种写法:

第一种:

<collection property="picUrls"  column="id" select="findPics" />
其中,column必填,为传递参数,在select指定的方法中需要用到,select指定的方法的写法应该为:mapper内的地址+方法名
我这里是因为指定的方法在同一个mapper的xml文件中,所以简写了;
这里更完整的写法为:
 <collection property="picUrls" javaType="ArrayList" column="id" ofType="java.lang.String" select="com.ruiheng.admin.mapper.ImageTextMapper.addPics" />

<resultMap id="ListImageTextVO" type="com.ruiheng.admin.vo.imagetext.ListImageTextVO">
        <id column="id" property="id" jdbcType="VARCHAR"/>
        <result column="itype" property="itype" jdbcType="INTEGER"/>
        <result column="title" property="title" jdbcType="VARCHAR"/>
        <collection property="picUrls"  column="id" select="findPics" />
    </resultMap>

    <select id="findList" resultMap="ListImageTextVO" >
        SELECT it.* FROM t_image_text it
</select> <resultMap id="picUrls" type="String" > <result column="pic_url" property="picUrl"/> </resultMap> <select id="findPics" resultMap="picUrls"> select pic_url from t_third_pic where third_id=#{id} </select>

 

第二种:

<collection property="picUrls" resultMap="picUrls" />
<resultMap id="ListImageTextVO" type="com.ruiheng.admin.vo.imagetext.ListImageTextVO">
        <id column="id" property="id" jdbcType="VARCHAR"/>
        <result column="itype" property="itype" jdbcType="INTEGER"/>
        <result column="title" property="title" jdbcType="VARCHAR"/>
        <collection property="picUrls" resultMap="picUrls" />
    </resultMap>

    <select id="findList" resultMap="ListImageTextVO" >
        SELECT it.* ,tp.pic_url FROM t_image_text it
JOIN t_third_pic tp ON tp.third_id
= it.id
</select> <resultMap id="picUrls" type="String" > <result column="pic_url" property="picUrl"/> </resultMap>

通过观察上面两种写法,很明显是第二种更简洁一些,不用单独写sql语句,直接在一个地方写就好了;当然,这是因为我查询的集合只包含简单的String 类型参数,如果这里是复杂的对象,

相对而言,第一种写法更灵活,思路清晰一些;所以具体情况应该具体对待

推荐阅读