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>

调用查询方法

相关推荐
hhb_6181 分钟前
C#高性能异步编程实战与底层原理深度解析
开发语言·c#
呱牛do it2 分钟前
企业级门户网站设计与实现:基于SpringBoot + Vue3的全栈解决方案(Day 4)
java·vue
云烟成雨TD4 分钟前
Spring AI Alibaba 1.x 系列【39】四大多智能体(Multi-agent)架构
java·人工智能·spring
Xingxing?!6 分钟前
Java 后端分层架构详解
java·架构·状态模式
雾岛听蓝10 分钟前
Qt操作指南:状态栏、浮动窗口与对话框使用
开发语言·经验分享·笔记·qt
_Evan_Yao16 分钟前
对话的边界:HTTP 的克制,SSE 的流淌,WebSocket 的自由
java·后端·websocket·网络协议·http
危桥带雨31 分钟前
FLASH代码部分
java·后端·spring
minji...38 分钟前
Linux 线程同步与互斥(五) 日志,线程池
linux·运维·服务器·开发语言·c++·算法
逍遥德1 小时前
skill模板-基于java maven项目
java·人工智能·自然语言处理·maven
兩尛1 小时前
c++面试常问2
开发语言·c++·面试