Loading

mybatis 查询返回的类型中字段类型为 List<xx>

基本类型数组

mapper.xml

<resultMap id="xxDtoResultMap"
           type="com.xx.xxDto">
    <id property="id" column="id" jdbcType="INTEGER"/>
    <result property="roomCount" column="room_count" jdbcType="INTEGER"/>
    <collection property="roomIds" ofType="Integer">
        <result column="room_ids"/>
    </collection>
</resultMap>

<select id="list" resultMap="xxDtoResultMap">
    select
    id
    count(xx.id) as room_count,
    room.id as room_ids
    ....
</select>

自定义类型数组

Vo

package cn.myesn.pojo.vo;

import lombok.Data;

import java.util.List;

/**
 * 二级分类 VO
 */
@Data
public final class CategoryVo {

    private Integer id;
    private String name;
    private String type;
    private Integer fatherId;
    private List<SubCategoryVo> subCategories;

    @Data
    public static final class SubCategoryVo{
        private Integer subId;
        private String subName;
        private String subType;
        private Integer subFatherId;
    }
}

mapper.xml

<resultMap id="myCategoryVo" type="cn.myesn.pojo.vo.CategoryVo">
  <id column="id" property="id" jdbcType="INTEGER" />
  <result column="name" property="name" jdbcType="VARCHAR" />
  <result column="type" property="type" jdbcType="INTEGER" />
  <result column="fatherId" property="fatherId" jdbcType="INTEGER" />
  <collection property="subCategories" ofType="cn.myesn.pojo.vo.CategoryVo$SubCategoryVo">
    <id column="subId" property="subId" jdbcType="INTEGER" />
    <result column="subName" property="subName" jdbcType="VARCHAR" />
    <result column="subType" property="subType" jdbcType="INTEGER" />
    <result column="subFatherId" property="subFatherId" jdbcType="INTEGER" />
  </collection>
</resultMap>

<select id="getSubCategories" resultMap="myCategoryVo" parameterType="int">
  select
    f.id  as id,
    f.name as name,
    f.`type` as `type`,
    f.father_id  as fatherId,
    c.id as subId,
    c.name as subName,
    c.`type` as subType,
    c.father_id as subFatherId
  from category f
  left join category c on f.id = c.father_id
  where f.father_id = #{rootCategoryId}
</select>

参考

select-list-of-integers-as-collection-inside-another-result-map-in-mybatis

mybatis 对象 List List属性 映射

posted @ 2021-07-23 13:05  myEsn2E9  阅读(844)  评论(0编辑  收藏  举报