在 MyBatis 中,通过 <resultMap> 元素的子元素 <collection> 处理一对多级联关系,collection 可以将关联查询的多条记录映射到一个 list 集合属性中。示例代码如下
<collection property="orderList"
ofType="net.cc.po.Order" column="id"
select="net.cc.mapper.OrderMapper.selectOrderById" />
在 <collection> 元素中通常使用以下属性。
- property:指定映射到实体类的对象属性。
- column:指定表中对应的字段(即查询返回的列名)。
- javaType:指定映射到实体对象属性的类型。
- select:指定引入嵌套查询的子 SQL 语句,该属性用于关联映射中的嵌套查询。
一对多关联查询可采用以下两种方式:
- 分步查询,通过两次或多次查询,为一对多关系的实体 Bean 赋值
- 单步查询,通过关联查询实现
示例
以用户和订单为例讲解一对多关联查询(实现“根据 id 查询用户及其关联的订单信息”的功能)的处理过程。
1)创建数据表
需要两张数据表,一张是用户表 user,一张是订单表 order,这两张表具有一对多的级联关系,创建过程省略。
创建持久化类
创建持久化类 User 和 Order,代码分别如下
//User 类
public class User {
private int id;
private String name;
private String pwd;
private List<Order> orderList;
/*省略setter和getter方法*/
@Override
public String toString() {
return "User [id=" + id + ", name=" + name + ", orderList=" + orderList + "]";
}
}
//Order 类
public class Order {
private int id;
private int ordernum;
/*省略setter和getter方法*/
@Override
public String toString() {
return "Order [id=" + id + ", ordernum=" + ordernum + "]";
}
}
分步查询
OrderMapper 类代码如下
public List<Order> selectOrderById(int id);
OrderMapper.xml 中相应的映射 SQL 语句
<!-- 根据id查询订单信息 -->
<select id="selectOrderById" resultType="net.cc.po.Order"
parameterType="Integer">
SELECT * FROM `order` where userId=#{id}
</select>
UserMapper 类
public User selectUserOrderById1(int id);
UserMapper.xml 中相应的映射 SQL 语句
<!-- 一对多 根据id查询用户及其关联的订单信息:级联查询的第一种方法(分步查询) -->
<resultMap type="net.cc.po.User" id="userAndOrder1">
<id property="id" column="id" />
<result property="name" column="name" />
<result property="pwd" column="pwd" />
<!-- 一对多级联查询,ofType表示集合中的元素类型,将id传递给selectOrderById -->
<collection property="orderList"
ofType="net.cc.po.Order" column="id"
select="net.cc.mapper.OrderMapper.selectOrderById" />
</resultMap>
<select id="selectUserOrderById1" parameterType="Integer"
resultMap="userAndOrder1">
select * from user where id=#{id}
</select>
测试:
public class Test {
public static void main(String[] args) throws IOException {
InputStream config = Resources.getResourceAsStream("mybatis-config.xml");
SqlSessionFactory ssf = new SqlSessionFactoryBuilder().build(config);
SqlSession ss = ssf.openSession();
User us = ss.getMapper(UserMapper.class).selectUserOrderById1(1);
System.out.println(us);
}
}
运行结果:
DEBUG [main] - ==> Preparing: select * from user where id=?
DEBUG [main] - ==> Parameters: 1(Integer)
DEBUG [main] - ====> Preparing: SELECT * FROM `order` where userId=?
DEBUG [main] - ====> Parameters: 1(Integer)
DEBUG [main] - <==== Total: 2
DEBUG [main] - <== Total: 1
User [id=1, name=测试1, orderList=[Order [id=0, ordernum=20200107], Order [id=0, ordernum=20200645]]]
单步查询
该种方式实现一对多关联查询需要修改 Order 持久化类,因为 Order 中的 id 不能和 User 中的 id 重复
public class Order {
private int oId;
private int ordernum;
/*省略setter和getter方法*/
@Override
public String toString() {
return "Order [id=" + oId+ ", ordernum=" + ordernum + "]";
}
}
UserMapper.xml 中相关映射 SQL 语句如下
<!-- 一对多 根据id查询用户及其关联的订单信息:级联查询的第二种方法(单步查询) -->
<resultMap type="net.cc.po.User" id="userAndOrder2">
<id property="id" column="id" />
<result property="name" column="name" />
<result property="pwd" column="pwd" />
<!-- 一对多级联查询,ofType表示集合中的元素类型 -->
<collection property="orderList"
ofType="net.cc.po.Order">
<id property="oId" column="oId" />
<result property="ordernum" column="ordernum" />
</collection>
</resultMap>
<select id="selectUserOrderById2" parameterType="Integer"
resultMap="userAndOrder2">
SELECT u.*,o.id as oId,o.ordernum FROM `user` u,`order` o
WHERE
u.id=o.`userId` AND u.id=#{id}
</select>
测试:
public class Test {
public static void main(String[] args) throws IOException {
InputStream config = Resources.getResourceAsStream("mybatis-config.xml");
SqlSessionFactory ssf = new SqlSessionFactoryBuilder().build(config);
SqlSession ss = ssf.openSession();
User us = ss.getMapper(UserMapper.class).selectUserOrderById2(1);
System.out.println(us);
}
}
DEBUG [main] - ==> Preparing: SELECT u.*,o.id as oId,o.ordernum FROM `user` u,`order` o WHERE u.id=o.`userId` AND u.id=?
DEBUG [main] - ==> Parameters: 1(Integer)
DEBUG [main] - <== Total: 2
User [id=1, name=测试1, orderList=[Order [id=1, ordernum=20200107], Order [id=4, ordernum=20200645]]]