MyBatis复杂映射开发之一对多查询
...大约 3 分钟
一对多查询模型
用户和订单表的关系为,一个用户有多个订单,一个订单只能属于一个用户。
一对多查询需求:查询多有用户,与此同时查询用户具有的订单信息。
一对多查询语句
对应的sql语句
select u.*,o.ordertime,o.total,o.uid from user u left join orders o on u.id = o.uid;
查询结果如下:
id | username | password | birthday | ordertime | total | uid |
---|---|---|---|---|---|---|
1 | lucy | 123 | 2022-03-17 17:15:56 | 2022-03-17 17:15:33 | 3000 | 1 |
1 | lucy | 123 | 2022-03-17 17:15:56 | 2022-03-17 17:15:33 | 4000 | 1 |
2 | tom | 123 | 2022-03-17 17:15:56 | 2022-03-17 17:15:33 | 5000 | 2 |
代码实现
修改User实体
创建UserMapper
配置UserMapper.xml
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.terwergreen.mapper.UserMapper">
<resultMap id="userMap" type="com.terwergreen.pojo.User">
<result property="id" column="id"></result>
<result property="username" column="username"></result>
<collection property="orderList" ofType="com.terwergreen.pojo.Order">
<result property="id" column="uid"></result>
<result property="orderTime" column="ordertime"></result>
<result property="total" column="total"></result>
</collection>
</resultMap>
<!-- resultMap:手动配置实体属性与表字段的映射关系 -->
<select id="findAll" resultMap="userMap">
select u.*,o.ordertime,o.total,o.uid from user u left join orders o on u.id = o.uid
</select>
</mapper>
测试
执行结果
文章更新历史
2022/05/08 feat:新增Kotlin支持
Powered by Waline v2.14.9