MyBatis复杂映射开发之一对一查询
...大约 3 分钟
一对一查询需求
用户表和订单表的关系为:一个用户可以有多个订单,一个订单只能从属于一个用户
一对一查询需求:查询一个订单,同时查询出该订单所对应的用户
对应的sql语句:select * from orders o,user u where o.uid=u.id
查询结果如下:
id | ordertime | total | uid | id | username | password | birthday |
---|---|---|---|---|---|---|---|
1 | 2022-03-17 17:15:33 | 3000 | 1 | 1 | lucy | 123 | 2022-03-17 17:15:56 |
2 | 2022-03-17 17:15:33 | 4000 | 1 | 1 | lucy | 123 | 2022-03-17 17:15:56 |
3 | 2022-03-17 17:15:33 | 5000 | 2 | 2 | tom | 123 | 2022-03-17 17:15:56 |
需求分析
具体实现
创建User和Order实体
User
Order
创建OrderMapper接口
配置OrderMapper.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.OrderMapper">
<resultMap id="orderMap" type="com.terwergreen.pojo.Order">
<result property="id" column="id"></result>
<result property="orderTime" column="ordertime"></result>
<result property="total" column="total"></result>
<association property="user" javaType="com.terwergreen.pojo.User">
<result property="id" column="uid"></result>
<result property="username" column="username"></result>
</association>
</resultMap>
<!-- resultMap:手动配置实体属性与表字段的映射关系 -->
<select id="findOrderAndUser" resultMap="orderMap">
select * from orders o,user u where o.uid=u.id
</select>
</mapper>
另外一种配置方法
<mapper namespace="com.terwergreen.mapper.OrderMapper">
<resultMap id="orderMap" type="com.terwergreen.pojo.Order">
<result property="id" column="id"></result>
<result property="orderTime" column="ordertime"></result>
<result property="total" column="total"></result>
<result property="user.id" column="uid"></result>
<result property="user.username" column="username"></result>
</resultMap>
<!-- resultMap:手动配置实体属性与表字段的映射关系 -->
<select id="findOrderAndUser" resultMap="orderMap">
select * from orders o,user u where o.uid=u.id
</select>
</mapper>
测试结果
文章更新历史
2022/05/08 feat:新增Kotlin支持
Powered by Waline v2.14.9