mybaits ResultMap 使用collection属性的select参数方式实现嵌套List查询

mybaits ResultMap 使用collection属性的select参数方式实现嵌套List查询


前言


使用了 collection 元素来定义了 select 属性,实际上这个属性会执行一个独立的查询,而不再需要在主查询中使用 LEFT JOIN 来获取关联的数据。

示例



<resultMap id="ResultMap" type="com.laoye.touchFish.entity.User">
   <id column="id" jdbcType="INTEGER" property="id"/>
   <result column="name" jdbcType="VARCHAR" property="name"/>
   <result column="user_name" jdbcType="VARCHAR" property="userName"/>
   <result column="path" jdbcType="VARCHAR" property="path"/>
   <result column="description" jdbcType="VARCHAR" property="description"/>
   <result column="status" jdbcType="TINYINT" property="status"/>
   <result column="update_time" jdbcType="TIMESTAMP" property="updateTime"/>
   <result column="create_time" jdbcType="TIMESTAMP" property="createTime"/>
   <collection property="posts" ofType="com.laoye.touchFish.entity.Post" column="id" select="selectByUserRecordId"/>
</resultMap>


<resultMap id="postMap" type="com.laoye.touchFish.entity.Post">
   <id column="id" jdbcType="INTEGER" property="id" />
   <result column="user_id" jdbcType="INTEGER" property="userId" />
   <result column="post_name" jdbcType="VARCHAR" property="postName" />
   <result column="path" jdbcType="VARCHAR" property="path" />
   <result column="create_time" jdbcType="TIMESTAMP" property="createTime" />
</resultMap>

<select id="selectByUserRecordId" parameterType="java.lang.Integer" resultMap="postMap">
    select
    p.id, p.user_id, p.post_name, p.`path`
    from post p
    where p.user_id = #{id,jdbcType=INTEGER}
</select>

<select id="selectList" resultMap="ResultMap">
    select
    u.id, u.name, u.user_name, u.`path`, u.description, u.`status`, u.update_time, u.create_time
    from user u
    <where>
        <if test="status != null and status != ''">
            and u.`status` = #{status}
        </if>
    </where>
    ORDER BY create_time desc
</select>

public class User {
    private Long id;
    private String name;
    private String username;
    private String path;
    private String description;
    private Integer status;
    private Date createTime;
    private Date updateTime;
    private List<Post> posts;
    // getters and setters
}



public class Post {
    private Long id;
    private Long userId;
    private String postName;
    private String path;
    private Date createTime;
    // getters and setters
}

selectList返回的User数据里面自动包含Post属性的List



总结

  • 简化复杂查询,更加清晰
  • 优化sql,减少查询时间
  • 少量手敲避免报错
  • mybatis YYDS
  • 9
    点赞
  • 11
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值