首页 > 其他 > 详细

Mybatis 一对多查询(使用collection集合)

时间:2020-06-14 15:36:07      阅读:56      评论:0      收藏:0      [点我收藏+]

Mybatis处理一对多关系下的查询方法

封装结果集resultMap

假设一则新闻信息对应多个新闻图片
在新闻信息实体类下

public class Info_Img {
    private Integer infoId;

    private String content;

    private List<Img> imgs;
}

图片实体类

public class Img {
    private Integer imgId;

    private String url;

    private Integer infoId;//外键
}

映射SQLMapper xml文件的结果集resultMap写法

<resultMap id="BaseResultMap" type="com.example.project.entity.Info_Img">#type填写项目路径相应的实体类
    <id column="info_id" jdbcType="INTEGER" property="infoId" />
    <collection property="imgs"  ofType="com.example.project.entity.Img" javaType="java.util.ArrayList">
      <id column="img_id" jdbcType="INTEGER" property="imgId" />
      <result column="url" jdbcType="VARCHAR" property="url" />
      <result column="info_id" jdbcType="INTEGER" property="InfoId" />
    </collection>
  </resultMap>
<select id="findAll" resultMap="BaseResultMap">
    select
      b.info_id,
      i.img_id,i.url
    FROM
      info AS b,
      img AS i
  </select>

注意 :查询结果一定要含有主键id,以至于collection对结果进行合并处理成数组类型,且字段必须对应

Mybatis 一对多查询(使用collection集合)

原文:https://www.cnblogs.com/Faink/p/13121784.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!