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


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对结果进行合并处理成数组类型,且字段必须对应


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM