MyBatis 的一对多查询可以通过在 <resultMap> 标签中使用 <collection> 标签,将查询结果映射成 Java 对象的嵌套集合。

MyBatis 的一对多查询可以通过在 <resultMap> 标签中使用 <collection> 标签,将查询结果映射成 Java 对象的嵌套集合。具体步骤如下:

在 <resultMap> 中使用 <collection> 标签

在 <resultMap> 标签中使用 <collection> 标签,并指定 property 属性为嵌套集合的属性名,column 属性为关联表中的外键列名,javaType 属性为嵌套集合中元素的类型。

XML 复制代码
<resultMap id="BaseResultMap" type="com.example.goods_admin.entity.Goods">
        <id column="id" jdbcType="VARCHAR" property="id" />
        <result column="name" jdbcType="VARCHAR" property="name" />
        <result column="price" jdbcType="INTEGER" property="price" />
        <result column="status" jdbcType="VARCHAR" property="status" />
          <!-- 嵌套集合 -->
        <collection property="imageUrlList" ofType="com.example.goods_admin.entity.GoodsImg">
            <result property="imgId" column="imgId"/>
            <result property="goodsId" column="goodsId"/>
            <result property="imageName" column="imageName"/>
            <result property="imageUrl" column="imageUrl"/>
        </collection>
    </resultMap>

编写 SQL 查询语句

编写 SQL 查询语句,使用 JOIN 操作关联两张表

XML 复制代码
  <select id="selectGoods" resultMap="BaseResultMap" parameterType="com.example.goods_admin.entity.Goods">
        SELECT
        g.id,g.name,g.price,g.status,gi.goodsId ,gi.imageName,gi.imageUrl,gi.imgId
        FROM
        goods g
        LEFT JOIN goods_img gi ON g.id = gi.goodsId
        <where>
            g.`status`='1'

            <if test="keyWord !=null and keyWord!=''">
                and g.name like concat('%', #{keyWord}, '%')
            </if>
            <if test="id !=null and id!=''">
                and g.id =#{id} and gi.`status`='1'
            </if>
        </where>
    </select>

调用查询方法

相关推荐
装不满的克莱因瓶22 分钟前
【从零搭建】AI大模型之ReactAgent智能体对接MCP实战
java·人工智能·ai·springai·mcp·springaialibaba
Risehuxyc30 分钟前
来自PHP项目devnexen的回信
开发语言·php
FRing031 小时前
vue2干货总结10(json-server、vant-ui、postcss插件、axios二次封装、图形验证码、toast轻提示)
开发语言·前端·vue.js·ui·json·vue2·postcss
SimonKing1 小时前
AI Assistant被"隐藏"了?别慌,IDEA 2026.3 这波是换了个脑子
java·后端·程序员
我是大猴子1 小时前
分析sss
开发语言
Resean02231 小时前
SpringMVC 6+源码分析(九)异常处理
java·spring·springmvc
geats人山人海1 小时前
现代c++4.1
java·开发语言·c++
布莱克6052 小时前
Swift 字符串详解:从基础用法到性能与最佳实践
服务器·开发语言·ssh·字符串·swift
下一站春风里2 小时前
Spring IoC 控制反转 完整技术笔记
java·spring boot·笔记·spring
挖掘狂人2 小时前
用户连点两次「确认支付」,你的后端凭什么只扣一次钱?
java·后端·面试