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>

调用查询方法

相关推荐
vx-程序开发6 分钟前
springboot在线装修管理系统-计算机毕业设计源码56278
java·c语言·spring boot·python·spring·django·php
大傻^9 分钟前
Spring AI Alibaba 可观测性实践:AI应用监控与链路追踪
java·人工智能·后端·spring·springaialibaba
Dxy12393102169 分钟前
js如何把字符串转数字
开发语言·前端·javascript
云烟成雨TD14 分钟前
Spring AI Alibaba 1.x 系列【1】阿里巴巴 AI 生态
java·人工智能·spring
诗人不写诗18 分钟前
spring是如何组织切面的
java·后端·spring
_饭团27 分钟前
字符串函数全解析:12 种核心函数的使用与底层模拟实现
c语言·开发语言·学习·考研·面试·蓝桥杯
Larry_Yanan28 分钟前
Qt网络开发之基于 QWebEngine 实现简易内嵌浏览器
linux·开发语言·网络·c++·笔记·qt·学习
2401_8318249634 分钟前
嵌入式C++驱动开发
开发语言·c++·算法
qingcyb40 分钟前
重复 id 对应的多个对象
开发语言·python
li星野1 小时前
[特殊字符] 模拟试卷一:C++核心与系统基础(90分钟)答案版
开发语言·c++·算法