MyBatis中关联关系查询sql写法

本文介绍MyBatis中实现各种关联查询的方法,包括一对多、多对一、自关联及多对多关系的数据获取策略。文章详细展示了如何使用XML映射文件定义查询逻辑,以及如何通过连接查询和独立查询两种方式实现数据的高效加载。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

MyBatis中关联关系查询sql写法

一,一对多关系查询(以country与minister关系为例)

1,通过多表连接查询方式实现

 XML Code 
1
2
3
4
5
6
7
8
9
10
11
12
<resultMap type="Country" id="countryMapper">
  <id column="cid" property="cid" />
  <result column="cname" property="cname" />
  <collection property="ministers" ofType="Minister">
    <id column="mid" property="mid" />
    <result column="mname" property="mname" />
  </collection>
</resultMap>
<select id="selectCountryById" resultMap="countryMapper">
    select cid,cname,mid,mname from country,minister where countryId=cid and cid=#{xxx}
</select>

2,通过多表单独查询方式实现(开发中常用这种方式)

 XML Code 
1
2
3
4
5
6
7
8
9
10
<select id="selectMinisterByCountry" resultType="Minister">
 select mid,mname from minister where countryId=#{ooo}
</select>
<resultMap type="Country" id="countryMapper">
  <id column="cid" property="cid" />
  <result column="cname" property="cname" />
  <collection property="ministers" ofType="Minister" select="selectMinisterByCountry" column="cid" />
</resultMap>
<select id="selectCountryById" resultMap="countryMapper">
    select cid,cname from country where cid=#{xxx}
</select>

二、多对一关系查询(以country与minister关系为例)

1,通过多表连接查询方式实现

 XML Code 
1
2
3
4
5
6
7
8
9
10
11
12
<resultMap type="Minister" id="ministerMapper">
  <id column="mid" property="mid" />
  <result column="mname" property="mname" />
  <association property="country" javaType="Country">
    <id column="cid" property="cid" />
    <result column="cname" property="cname" />
  </association>
</resultMap>
<select id="selectMinisterById" resultMap="ministerMapper">
    select mid,mname,cid,cname from minister, country where countryId=cid and mid=#{xxx}
</select>

2,通过多表单独查询方式实现

 XML Code 
1
2
3
4
5
6
7
8
9
10
11
12
<select id="selectCountryById" resultType="Country">
    select cid,cname from country where cid=#{ooo}
</select>
<resultMap type="Minister" id="ministerMapper">
  <id column="mid" property="mid" />
  <result column="mname" property="mname" />
  <association property="country" javaType="Country" select="selectCountryById" column="countryId" />
</resultMap>
<select id="selectMinisterById" resultMap="ministerMapper">
    select mid,mname,countryId from minister where mid=#{xxx}
</select>

三、自关联查询(以NewsLabel为例)

1,以一对多方式实现-查询指定栏目的所有子孙栏目

 XML Code 
1
2
3
4
5
6
7
8
9
<resultMap type="NewsLabel" id="newslabelMapper">
  <id column="id" property="id" />
  <result column="name" property="name" />
  <collection property="children" ofType="NewsLabel" select="selectChildrenByParent" column="id" />
</resultMap>
<select id="selectChildrenByParent" resultMap="newslabelMapper">
    select id,name from newslabel where pid=#{xxx}
</select>

2,以一对多方式实现-查询指定栏目及其所有子孙栏目

 XML Code 
1
2
3
4
5
6
7
8
9
10
11
12
<select id="selectNewslabelByParent" resultMap="newslabelMapper">
    select id,name from newslabel where pid=#{ooo}
</select>
<resultMap type="NewsLabel" id="newslabelMapper">
  <id column="id" property="id" />
  <result column="name" property="name" />
  <collection property="children" ofType="NewsLabel" select="selectNewslabelByParent" column="id" />
</resultMap>
<select id="selectNewsLabelById" resultMap="newslabelMapper">
    select id,name from newslabel where id=#{xxx}
</select>

3,以多对一方式实现

 XML Code 
1
2
3
4
5
6
7
8
9
<resultMap type="NewsLabel" id="newslabelMapper">
  <id column="id" property="id" />
  <result column="name" property="name" />
  <association property="parent" javaType="NewsLabel" select="selectNewsLabelById" column="pid" />
</resultMap>
<select id="selectNewsLabelById" resultMap="newslabelMapper">
    select id,name,pid from newslabel where id=#{xxx}
</select>

四、多对多关系查询(以student与course为例)

 XML Code 
1
2
3
4
5
6
7
8
9
10
11
12
<resultMap type="Student" id="studentMapper">
  <id column="sid" property="sid" />
  <result column="sname" property="sname" />
  <collection property="courses" ofType="Course">
    <id column="cid" property="cid" />
    <result column="cname" property="cname" />
  </collection>
</resultMap>
<select id="selectStudentById" resultMap="studentMapper">
    select sid,sname,cid,cname from student,middle,course where sid=studentId and cid=courseId and sid=#{xxx}
</select>

### MyBatis 中实现关联查询的方法与示例 MyBatis 是一种强大的持久化框架,能够简化 Java 应用程序中的数据库操作。它支持多种类型的关联查询,包括一对一、一对多以及多对多的关系。 #### 1. **一对一关联查询** 在一对一关系中,可以通过 `resultMap` 配置来完成映射。假设有一个用户表 (`User`) 和一个订单表 (`Order`),其中每个用户只对应一个订单: ```xml <resultMap id="userWithOrderResultMap" type="com.example.User"> <id property="userId" column="user_id"/> <result property="username" column="username"/> <!-- 关联 Order 表 --> <association property="order" javaType="com.example.Order"> <id property="orderId" column="order_id"/> <result property="amount" column="amount"/> </association> </resultMap> <select id="getUserWithOrderById" resultMap="userWithOrderResultMap"> SELECT u.user_id, u.username, o.order_id, o.amount FROM user u LEFT JOIN orders o ON u.user_id = o.user_id WHERE u.user_id = #{userId} </select> ``` 此代码片段展示了一对一的关联查询方式[^1]。 --- #### 2. **一对多关联查询** 对于一对多关系,比如一个分类 (`Category`) 对应多个商品 (`Product`),可以使用 `<collection>` 标签来进行配置: ```xml <resultMap id="categoryWithProductsResultMap" type="com.example.Category"> <id property="categoryId" column="category_id"/> <result property="name" column="category_name"/> <!-- 多个 Product 的集合 --> <collection property="products" ofType="com.example.Product"> <id property="productId" column="product_id"/> <result property="productName" column="product_name"/> <result property="price" column="price"/> </collection> </resultMap> <select id="getCategoryWithProductsById" resultMap="categoryWithProductsResultMap"> SELECT c.category_id, c.category_name, p.product_id, p.product_name, p.price FROM category c LEFT JOIN product p ON c.category_id = p.category_id WHERE c.category_id = #{categoryId} </select> ``` 这段代码实现了通过类别 ID 查询该类别的所有商品的功能[^1]。 --- #### 3. **多对多关联查询** 当两个实体之间存在多对多关系时,通常会引入一张中间表作为桥梁。例如,角色 (`Role`) 和权限 (`Permission`) 之间的多对多关系可通过如下方式进行配置: ```java @Test public void testManyToMany() { RoleDao roleDao = sqlSession.getMapper(RoleDao.class); List<Role> roleList = roleDao.findAll(); for (Role role : roleList) { System.out.println(role); } } ``` 对应的 XML 映射文件可能如下所示: ```xml <resultMap id="roleWithPermissionsResultMap" type="com.example.Role"> <id property="roleId" column="role_id"/> <result property="roleName" column="role_name"/> <!-- 权限列表 --> <collection property="permissions" ofType="com.example.Permission"> <id property="permissionId" column="permission_id"/> <result property="permissionName" column="permission_name"/> </collection> </resultMap> <select id="findAllRolesWithPermissions" resultMap="roleWithPermissionsResultMap"> SELECT r.role_id, r.role_name, p.permission_id, p.permission_name FROM roles r LEFT JOIN role_permission rp ON r.role_id = rp.role_id LEFT JOIN permissions p ON rp.permission_id = p.permission_id </select> ``` 这里展示了如何利用嵌套的结果集处理多对多关系[^4]。 --- #### 4. **动态 SQL 支持复杂条件过滤** 如果需要进一步增强灵活性,可以在查询中加入动态 SQL 功能。例如,在查询某个用户的订单时增加时间范围筛选条件: ```sql <select id="findOrdersByUserIdAndDateRange" parameterType="map" resultType="com.example.Order"> SELECT * FROM orders WHERE user_id = #{userId} <if test="startDate != null and endDate != null"> AND order_date BETWEEN #{startDate} AND #{endDate} </if> </select> ``` 这种写法允许开发者根据实际情况调整查询逻辑[^2]。 --- #### 总结 通过对 MyBatis 的深入学习和实践,可以发现其提供了非常丰富的工具用于解决各种复杂的业务场景下的数据访问问题。无论是简单的单表查询还是涉及多方联动的数据提取过程,都可以借助于它的强大特性得以高效实现[^3]。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值