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>

调用查询方法

相关推荐
用户0332126663675 分钟前
Java添加、设置和删除PDF图层:
java
foundbug99911 分钟前
基于CSMA-CA协议的V2X通信MATLAB仿真
开发语言·网络·matlab
荣光波比13 分钟前
K8S(十)—— Kubernetes核心组件详解:Pod控制器与配置资源管理
java·容器·kubernetes
m0_6515939121 分钟前
企业级订单系统架构设计:领域驱动 vs 数据驱动实践指南
java·系统架构·领域驱动ddd
WangMing_X21 分钟前
C#上位机软件:2.5 体验CLR实现多语言混合编程
java·开发语言·c#
jerryinwuhan24 分钟前
pybullet入门到入门_1
开发语言·人工智能·python
青云交31 分钟前
Java 大视界 -- Java 大数据在智慧交通停车场智能管理与车位预测中的应用实践
java·数据采集·数据清洗·智慧交通·停车场智能管理·智能收费系统·车位预测
豐儀麟阁贵37 分钟前
4.4数组的基本操作
java·开发语言·数据结构·算法
Moniane38 分钟前
XMW技术:颠覆未来的创新引擎
开发语言
组合缺一42 分钟前
全球首个支持 IETF JSONPath (RFC 9535) 标准的 Java 框架,Snack4-Jsonpath v4.0.0 发布
java·开发语言·json·jsonpath