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>

调用查询方法

相关推荐
UP_Continue3 分钟前
C++--List的模拟实现
开发语言·c++
你我约定有三7 分钟前
spring--xml注入时bean的property属性
xml·java·spring
小雪_Snow8 分钟前
正则表达式
java
Codebee9 分钟前
OneCode 3.0 VFS客户端驱动(SDK)技术解析:从架构到实战
java·后端·架构
双叶83644 分钟前
(C++)STL标准库(vector动态数组)(list列表)(set集合)(map键值对)相关对比,基础教程
c语言·开发语言·数据结构·c++·list
喜欢敲代码的程序员1 小时前
Spring Boot中请求参数读取方式
java·spring boot·后端·spring
爬点儿啥1 小时前
[爬虫知识] 深入理解多进程/多线程/协程的异步逻辑
开发语言·爬虫·python·多线程·协程·异步·多进程
唐不是营养物质1 小时前
Apache POI 的 HSSFWorkbook、SXSSFWorkbook和XSSFWorkbook三者的区别
java
樽酒ﻬق2 小时前
Prometheus Operator:Kubernetes 监控自动化实践
java·算法·云原生·运维开发
有梦想的攻城狮2 小时前
快速搭建Maven仓库服务
java·maven·仓库·nexus