- 单表查询3种方式详解
- 一对一关联查询(4种方式)详解
- 一对多查询(2种方式)详解
- 综合案例
- 总结
- 建议
- 源码
- 建库建表
创建一个数据库: javacode2020
4张表:
t_user(用户表)
t_goods(商品表)
t_order(订单表)
t_order_detail(订单明细表)
表之间的关系:
t_order和t_user是一对一的关系,一条订单关联一个用户记录
t_order和t_order_detail是一对多关系,每个订单中可能包含多个子订单,每个子订单一个商品
DROP DATABASE IF EXISTS `javacode`;
CREATE DATABASE `javacode`;
USE `javacode`;
DROP TABLE IF EXISTS t_user;
CREATE TABLE t_user(
id int AUTO_INCREMENT PRIMARY KEY COMMENT '用户id',
name VARCHAR() NOT NULL DEFAULT '' COMMENT '用户名'
) COMMENT '用户表';
INSERT INTO t_user VALUES (,'张学友'),(2,'路人甲Java');
DROP TABLE IF EXISTS t_goods;
CREATE TABLE t_goods(
id int AUTO_INCREMENT PRIMARY KEY COMMENT '商品id',
name VARCHAR() NOT NULL DEFAULT '' COMMENT '商品名称',
price DECIMAL(,2) NOT NULL DEFAULT 0 COMMENT '商品价格'
) COMMENT '商品信息表';
INSERT INTO t_goods VALUES (,'Mybatis系列',8.88),(2,'maven高手系列',16.66);
DROP TABLE IF EXISTS t_order;
CREATE TABLE t_order(
id int AUTO_INCREMENT PRIMARY KEY COMMENT '订单id',
user_id INT NOT NULL DEFAULT COMMENT '用户id,来源于t_user.id',
create_time BIGINT NOT NULL DEFAULT COMMENT '订单创建时间(时间戳,秒)',
up_time BIGINT NOT NULL DEFAULT COMMENT '订单最后修改时间(时间戳,秒)'
) COMMENT '订单表';
INSERT INTO t_order VALUES (,2,unix_timestamp(now()),unix_timestamp(now())),(2,1,unix_timestamp(now()),unix_timestamp(now()));
DROP TABLE IF EXISTS t_order_detail;
CREATE TABLE t_order_detail(
id int AUTO_INCREMENT PRIMARY KEY COMMENT '订单明细id',
order_id INT NOT NULL DEFAULT COMMENT '订单id,来源于t_order.id',
goods_id INT NOT NULL DEFAULT COMMENT '商品id,来源于t_goods.id',
num INT NOT NULL DEFAULT COMMENT '商品数量',
total_price DECIMAL(,2) NOT NULL DEFAULT 0 COMMENT '商品总金额'
) COMMENT '订单表';
INSERT INTO t_order_detail VALUES (,1,1,2,17.76),(2,1,1,1,16.66),(3,2,1,1,8.88);
select * from t_user;
select * from t_goods;
select * from t_order;
select * from t_order_detail;
单表查询(3种方式)
需求
需要按照订单id查询信息。
方式1
创建每个表对应的模型
db中表的字段是采用下划线划分的,模型中我们是采用骆驼命名法来的,例如 OrderModel :
package com.javacode.chat05.demo1.model;
import lombok.*;
import java.util.List;
@Getter
@Setter
@Builder
@ToString
@NoArgsConstructor
@AllArgsConstructor
public class OrderModel {
private Integer id;
private Integer userId;
private Long createTime;
private Long upTime;
}
其他几个模特也类似。
映射器xml
<select id="getById" resultType="com.javacode.chat05.demo1.model.OrderModel">
<![CDATA[
SELECT a.id,a.user_id as userId,a.create_time createTime,a.up_time upTime FROM t_order a WHERE a.id = #{value}
]]>
</select>
注意上面的 resultType ,标明结果的类型。
Mapper接口方法
OrderModel getById(int id);
mybatis全局配置文件
<?xml version=".0" encoding="UTF-8" ?>
<!DOCTYPE configuration
PUBLIC "-//mybatis.org//DTD Config .0//EN"
"#;>
<configuration>
<!-- 引入外部jdbc配置 -->
<properties resource="jdbc.properties"/>
<!-- 环境配置,可以配置多个环境 -->
<environments default="demo">
<environment id="demo">
<!-- 事务管理器工厂配置 -->
<transactionManager type="JDBC"/>
<!-- 数据源工厂配置,使用工厂来创建数据源 -->
<dataSource type="POOLED">
<property name="driver" value="${jdbc.driver}"/>
<property name="url" value="${jdbc.url}"/>
<property name="username" value="${jdbc.username}"/>
<property name="password" value="${jdbc.password}"/>
</dataSource>
</environment>
</environments>
<mappers>
<mapper resource="demo/mapper/UserMapper.xml" />
<mapper resource="demo/mapper/GoodsMapper.xml" />
<mapper resource="demo/mapper/OrderMapper.xml" />
<mapper resource="demo/mapper/OrderDetailMapper.xml" />
</mappers>
</configuration>
测试用例
com.javacode.chat05.demo1.Demo1Test#getById
@Before
public void before() throws IOException {
//指定mybatis全局配置文件
String resource = "demo/mybatis-config.xml";
//读取全局配置文件
InputStream inputStream = Resources.getResourceAsStream(resource);
//构建SqlSessionFactory对象
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
this.sqlSessionFactory = sqlSessionFactory;
}
@Test
public void getById() {
try (SqlSession sqlSession = this.sqlSessionFactory.openSession(true);) {
OrderMapper mapper = sqlSession.getMapper(OrderMapper.class);
OrderModel orderModel = mapper.getById();
log.info("{}", orderModel);
}
}
运行输出
:59.211 [main] DEBUG c.j.c.d.mapper.OrderMapper.getById - ==> Preparing: SELECT a.id,a.user_id as userId,a.create_time createTime,a.up_time upTime FROM t_order a WHERE a.id = ?
:59.239 [main] DEBUG c.j.c.d.mapper.OrderMapper.getById - ==> Parameters: 1(Integer)
:59.258 [main] DEBUG c.j.c.d.mapper.OrderMapper.getById - <== Total: 1
:59.258 [main] INFO c.j.chat05.demo1.Demo1Test - OrderModel(id=1, userId=2, createTime=1577947790, upTime=1577947790)
原理
sql中我们使用了一个别名,将 t_order 中的字段转换成和 OrderModel 中字段一样的名称,最终mybatis内部会通过反射,将查询根据名称到 OrderModel 中找到同名的结果,然后进行结果。
方式2
如果我们项目中对应的模型中的字段都采用骆驼可以命名,mybatis 中进行了一些配置,可以使表中的字段和对应的模型中骆驼的字段进行自动映射。
需要在mybatis的配置文件中加入下面的配置:
<settings>
<!-- 是否开启自动驼峰命名规则映射,及从xx_yy映射到xxYy -->
<setting name="mapUnderscoreToCamelCase" value="true"/>
</settings>
映射器xml
<select id="getById" resultType="com.javacode2020.chat05.demo1.model.OrderModel">
<![CDATA[
SELECT a.id,a.user_id,a.create_time,a.up_time FROM t_order a WHERE a.id = #{value}
]]>
</select>
注意上面的sql,我们没有写别名了,因为我们打开了自动地图,所以结果会按照下面的关系进行自动查询:
sql对应的字段 |
OrderModel 中的字段 |
ID |
ID |
用户身份 |
用户身份 |
创建时间 |
创建时间 |
正常运行时间 |
正常运行时间 |
映射器接口
OrderModel getById(int id);
测试用例
com.javacode.chat05.demo1.Demo1Test#getById1
@Test
public void getById() {
try (SqlSession sqlSession = this.sqlSessionFactory.openSession(true);) {
OrderMapper mapper = sqlSession.getMapper(OrderMapper.class);
OrderModel orderModel = mapper.getById(1);
log.info("{}", orderModel);
}
}
运行输出
:44.884 [main] DEBUG c.j.c.d.mapper.OrderMapper.getById1 - ==> Preparing: SELECT a.id,a.user_id,a.create_time,a.up_time FROM t_order a WHERE a.id = ?
:44.917 [main] DEBUG c.j.c.d.mapper.OrderMapper.getById1 - ==> Parameters: 1(Integer)
:44.935 [main] DEBUG c.j.c.d.mapper.OrderMapper.getById1 - <== Total: 1
:44.935 [main] INFO c.j.chat05.demo1.Demo1Test - OrderModel(id=1, userId=2, createTime=1577947790, upTime=1577947790)
输出中可以产生这个产生,sql中的字段是下划线的方式,或者derModel中的字段是骆驼的方法,结果也可以自动调试成功,就是 mapUnderscoreToCamelCase 的效果。
方式3
mapper xml resultMap 这个中定义了一个元素,通过元素可以定义查询结果的映射关系。
映射器xml
<resultMap id="orderModelMap" type="com.javacode2020.chat05.demo1.model.OrderModel">
<id column="id" property="id" />
<result column="user_id" property="userId" />
<result column="create_time" property="createTime" />
<result column="up_time" property="upTime" />
</resultMap>
<select id="getById" resultMap="orderModelMap2">
<![CDATA[
SELECT a.id,a.user_id,a.create_time,a.up_time FROM t_order a WHERE a.id = #{value}
]]>
</select>
上面 resultMap 有2个元素需要指定:
- id:resultMap标识
- type:将结果封装成什么类型,这里我们需要将结果分装为 OrderModel
注意上面的选择元素, resultMap 说明查询结果使用哪个 resultMap 进行映射,这里我们使用的是这样 orderModelMap2 ,结果会根据 orderModelMap2 关联的 resultMap 进行映射。
映射器接口
OrderModel getById(int id);
测试用例
com.javacode.chat05.demo1.Demo1Test#getById2
@Test
public void getById() {
try (SqlSession sqlSession = this.sqlSessionFactory.openSession(true);) {
OrderMapper mapper = sqlSession.getMapper(OrderMapper.class);
OrderModel orderModel = mapper.getById(1);
log.info("{}", orderModel);
}
}
运行输出
:12.518 [main] DEBUG c.j.c.d.mapper.OrderMapper.getById2 - ==> Preparing: SELECT a.id,a.user_id,a.create_time,a.up_time FROM t_order a WHERE a.id = ?
:12.546 [main] DEBUG c.j.c.d.mapper.OrderMapper.getById2 - ==> Parameters: 1(Integer)
:12.564 [main] DEBUG c.j.c.d.mapper.OrderMapper.getById2 - <== Total: 1
:12.564 [main] INFO c.j.chat05.demo1.Demo1Test - OrderModel(id=1, userId=2, createTime=1577947790, upTime=1577947790)
一对一关联查询(4种方式)
需求
通过id查询订单的时候,将订单订单关联的用户信息也返回。
我们修改一下 OrderModel 代码,内部添加一个 UserModel ,如下:
package com.javacode.chat05.demo2.model;
import lombok.*;
import java.util.List;
@Getter
@Setter
@Builder
@ToString
@NoArgsConstructor
@AllArgsConstructor
public class OrderModel {
private Integer id;
private Integer userId;
private Long createTime;
private Long upTime;
//下单用户信息
private UserModel userModel;
}
用户型号内容:
package com.javacode.chat05.demo2.model;
import lombok.*;
@Getter
@Setter
@Builder
@ToString
@NoArgsConstructor
@AllArgsConstructor
public class UserModel {
private Integer id;
private String name;
}
方式1
映射器xml
<resultMap id="orderModelMap" type="com.javacode2020.chat05.demo2.model.OrderModel">
<id column="id" property="id" />
<result column="user_id" property="userId"/>
<result column="create_time" property="createTime"/>
<result column="up_time" property="upTime"/>
<result column="user_id" property="userModel.id"/>
<result column="name" property="userModel.name"/>
</resultMap>
<select id="getById" resultMap="orderModelMap1">
<![CDATA[
SELECT
a.id,
a.user_id,
a.create_time,
a.up_time,
b.name
FROM
t_order a,
t_user b
WHERE
a.user_id = b.id
AND a.id = #{value}
]]>
</select>
注意重点在于上面的这两行:
<result column="user_id" property="userModel.id"/>
<result column="name" property="userModel.name"/>
这个地方使用到了级权限,多级之间用 . 进行引用,这里我们只有一级,可以有很多级。
映射器接口
OrderModel getById(int id);
测试用例
com.javacode.chat05.demo2.Demo2Test#getById1
@Before
public void before() throws IOException {
//指定mybatis全局配置文件
String resource = "demo/mybatis-config.xml";
//读取全局配置文件
InputStream inputStream = Resources.getResourceAsStream(resource);
//构建SqlSessionFactory对象
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
this.sqlSessionFactory = sqlSessionFactory;
}
@Test
public void getById() {
try (SqlSession sqlSession = this.sqlSessionFactory.openSession(true);) {
OrderMapper mapper = sqlSession.getMapper(OrderMapper.class);
OrderModel orderModel = mapper.getById(1);
log.info("{}", orderModel);
}
}
运行输出
:20.811 [main] DEBUG c.j.c.d.mapper.OrderMapper.getById1 - ==> Preparing: SELECT a.id, a.user_id, a.create_time, a.up_time, b.name FROM t_order a, t_user b WHERE a.user_id = b.id AND a.id = ?
:20.843 [main] DEBUG c.j.c.d.mapper.OrderMapper.getById1 - ==> Parameters: 1(Integer)
:20.861 [main] DEBUG c.j.c.d.mapper.OrderMapper.getById1 - <== Total: 1
:20.861 [main] INFO c.j.chat05.demo2.Demo2Test - OrderModel(id=1, userId=2, createTime=1577947790, upTime=1577947790, userModel=UserModel(id=2, name=路人甲Java))
方式2
这次我们需要使用映射器 xml 中另外一个元素 association ,这个元素可以配置关联对象的映射关系,看示例。
映射器xml
<resultMap id="orderModelMap" type="com.javacode2020.chat05.demo2.model.OrderModel">
<id column="id" property="id" />
<result column="user_id" property="userId"/>
<result column="create_time" property="createTime"/>
<result column="up_time" property="upTime"/>
<association property="userModel">
<id column="user_id" property="id"/>
<result column="name" property="name" />
</association>
</resultMap>
<select id="getById" resultMap="orderModelMap2">
<![CDATA[
SELECT
a.id,
a.user_id,
a.create_time,
a.up_time,
b.name
FROM
t_order a,
t_user b
WHERE
a.user_id = b.id
AND a.id = #{value}
]]>
</select>
注意上面下面这部分代码:
<association property="userModel">
<id column="user_id" property="id"/>
<result column="name" property="name" />
</association>
注意上面的 property 属性,这就是配置sql查询结果和 OrderModel.userModel 对象的映射关系,将 user_id 和 userModel中的id进行映射 , name和userModel中的name进行映射 。
映射器接口
OrderModel getById(int id);
测试用例
@Test
public void getById() {
try (SqlSession sqlSession = this.sqlSessionFactory.openSession(true);) {
OrderMapper mapper = sqlSession.getMapper(OrderMapper.class);
OrderModel orderModel = mapper.getById(1);
log.info("{}", orderModel);
}
}
运行结果
:44.896 [main] DEBUG c.j.c.d.mapper.OrderMapper.getById2 - ==> Preparing: SELECT a.id, a.user_id, a.create_time, a.up_time, b.name FROM t_order a, t_user b WHERE a.user_id = b.id AND a.id = ?
:44.925 [main] DEBUG c.j.c.d.mapper.OrderMapper.getById2 - ==> Parameters: 1(Integer)
:44.941 [main] DEBUG c.j.c.d.mapper.OrderMapper.getById2 - <== Total: 1
:44.942 [main] INFO c.j.chat05.demo2.Demo2Test - OrderModel(id=1, userId=2, createTime=1577947790, upTime=1577947790, userModel=UserModel(id=2, name=路人甲Java))
从结果的最后一行可以研磨,所有细分的值映射都是ok的。
方式3
先按照订单id查询订单数据,然后在通过组合订单中 user_id 去用户表用户数据,通过展示查询,生成目标结果,mybatis已经构建了这种操作,如下。
用户映射器.xml
我们先定义一个通过userid查询用户信息的select元素如下,
<select id="getById" resultType="comjavacode.chat05.demo2.model.UserModel">
<![CDATA[
SELECT id,name FROM t_user where id = #{value}
]]>
</select>
订单模型.xml
<resultMap id="orderModelMap" type="com.javacode2020.chat05.demo2.model.OrderModel">
<id column="id" property="id" />
<result column="user_id" property="userId"/>
<result column="create_time" property="createTime"/>
<result column="up_time" property="upTime"/>
<association property="userModel" select="com.javacode.chat05.demo2.mapper.UserMapper.getById" column="user_id" />
</resultMap>
<select id="getById" resultMap="orderModelMap3">
<![CDATA[
SELECT
a.id,
a.user_id,
a.create_time,
a.up_time
FROM
t_order a
WHERE
a.id = #{value}
]]>
</select>
OrderModel.userModel 的值来自另一个查询,这个是通过 association 元素的 select 属性指定的,这里的属性使用的是
com.javacode.chat05.demo2.mapper.UserMapper.getById
这个查询是有条件的,通过条件 association 的 column 进行传递的,传递此处的的英文 getById3 查询查询查询结果中的 user_id 字段。
映射器接口
OrderModel getById(int id);
测试用例
com.javacode.chat05.demo2.Demo2Test#getById3
@Test
public void getById() {
try (SqlSession sqlSession = this.sqlSessionFactory.openSession(true);) {
OrderMapper mapper = sqlSession.getMapper(OrderMapper.class);
OrderModel orderModel = mapper.getById(1);
log.info("{}", orderModel);
}
}
运行输出
:12.569 [main] DEBUG c.j.c.d.mapper.OrderMapper.getById3 - ==> Preparing: SELECT a.id, a.user_id, a.create_time, a.up_time FROM t_order a WHERE a.id = ?
:12.600 [main] DEBUG c.j.c.d.mapper.OrderMapper.getById3 - ==> Parameters: 1(Integer)
:12.619 [main] DEBUG c.j.c.d.mapper.UserMapper.getById - ====> Preparing: SELECT id,name FROM t_user where id = ?
:12.620 [main] DEBUG c.j.c.d.mapper.UserMapper.getById - ====> Parameters: 2(Integer)
:12.625 [main] DEBUG c.j.c.d.mapper.UserMapper.getById - <==== Total: 1
:12.625 [main] DEBUG c.j.c.d.mapper.OrderMapper.getById3 - <== Total: 1
:12.625 [main] INFO c.j.chat05.demo2.Demo2Test - OrderModel(id=1, userId=2, createTime=1577947790, upTime=1577947790, userModel=UserModel(id=2, name=路人甲Java))
从输出中可以进行2次查询,先按照订单id查询订单,然后通过订单记录中用户id去用户表查询用户信息,最终执行了2次查询。
方式4
方式3中给第二个查询传递了一个参数,如果需要给第二个查询传递多个参数怎么办呢?可以这么写
<association property="属性" select="查询对应的select的id" column="{key=父查询字段1,key2=父查询字段2,key3=父查询字段3}" />
相当于给了一个地图,子中需要用过地图的关键获取的条件,看案例:
订单映射器.xml
<resultMap id="orderModelMap" type="com.javacode2020.chat05.demo2.model.OrderModel">
<id column="id" property="id" />
<result column="user_id" property="userId"/>
<result column="create_time" property="createTime"/>
<result column="up_time" property="upTime"/>
<association property="userModel" select="com.javacode.chat05.demo2.mapper.UserMapper.getById1" column="{uid1=user_id,uid2=create_time}" />
</resultMap>
<select id="getById" resultMap="orderModelMap4">
<![CDATA[
SELECT
a.id,
a.user_id,
a.create_time,
a.up_time
FROM
t_order a
WHERE
a.id = #{value}
]]>
</select>
用户映射器.xml
<select id="getById" resultType="com.javacode2020.chat05.demo2.model.UserModel">
<![CDATA[
SELECT id,name FROM t_user where id = #{uid} and id = #{uid2}
]]>
</select>
映射器接口
OrderModel getById(int id);
测试用例
com.javacode.chat05.demo2.Demo2Test#getById4
@Test
public void getById() {
try (SqlSession sqlSession = this.sqlSessionFactory.openSession(true);) {
OrderMapper mapper = sqlSession.getMapper(OrderMapper.class);
OrderModel orderModel = mapper.getById(1);
log.info("{}", orderModel);
}
}
运行输出
:59.881 [main] DEBUG c.j.c.d.mapper.OrderMapper.getById4 - ==> Preparing: SELECT a.id, a.user_id, a.create_time, a.up_time FROM t_order a WHERE a.id = ?
:59.914 [main] DEBUG c.j.c.d.mapper.OrderMapper.getById4 - ==> Parameters: 1(Integer)
:59.934 [main] DEBUG c.j.c.d.mapper.UserMapper.getById1 - ====> Preparing: SELECT id,name FROM t_user where id = ? and id = ?
:59.934 [main] DEBUG c.j.c.d.mapper.UserMapper.getById1 - ====> Parameters: 2(Integer), 1577947790(Long)
:59.939 [main] DEBUG c.j.c.d.mapper.UserMapper.getById1 - <==== Total: 0
:59.939 [main] DEBUG c.j.c.d.mapper.OrderMapper.getById4 - <== Total: 1
:59.939 [main] INFO c.j.chat05.demo2.Demo2Test - OrderModel(id=1, userId=2, createTime=1577947790, upTime=1577947790, userModel=null)
输出中看一下第二个查询的条件,传过来的是第一个查询的 user_id和create_time 。
一对多查询(2种方式)
需求
可知订单id查询出订单信息,并且可以查询出订单明细列表。
先修改一下OrderModel代码,如下:
package com.javacode.chat05.demo3.model;
import lombok.*;
import java.util.List;
@Getter
@Setter
@Builder
@ToString
@NoArgsConstructor
@AllArgsConstructor
public class OrderModel {
private Integer id;
private Integer userId;
private Long createTime;
private Long upTime;
//订单详情列表
private List<OrderDetailModel> orderDetailModelList;
}
订单模型中添加了一个集合 orderDetailModelList 事件详情列表。
方式1
订单映射器.xml
<resultMap id="orderModelMap" type="com.javacode2020.chat05.demo3.model.OrderModel">
<id column="id" property="id"/>
<result column="user_id" property="userId"/>
<result column="create_time" property="createTime"/>
<result column="up_time" property="upTime"/>
<collection property="orderDetailModelList" ofType="com.javacode.chat05.demo3.model.OrderDetailModel">
<id column="orderDetailId" property="id"/>
<result column="order_id" property="orderId"/>
<result column="goods_id" property="goodsId"/>
<result column="num" property="num"/>
<result column="total_price" property="totalPrice"/>
</collection>
</resultMap>
<select id="getById" resultMap="orderModelMap1">
<![CDATA[
SELECT
a.id ,
a.user_id,
a.create_time,
a.up_time,
b.id orderDetailId,
b.order_id,
b.goods_id,
b.num,
b.total_price
FROM
t_order a,
t_order_detail b
WHERE
a.id = b.order_id
AND a.id = #{value}
]]>
</select>
注意上面的 getById1 中的sql,这个sql中使用到了 t_order和t_order_detail 连接中,这个sql中会返回多条结果,但是最后的结果会 orderModelMap1 进行映射,最后的结果返回一个 OrderModel 对象,关键是 collection 这个元素被定义为集合中元素的映射关系,有2个属性需要注意:
- 属性:对应的属性名称
- ofType:集合中元素的类型,这里是 OrderDetailModel
原则是这样的,注意 orderModelMap1 中告
<id column="id" property="id"/>
查询出来的结果会按照这个中指定的 column 进行结果,即按照配置任务进行结果 id ,每个订单对应的明细表,订单明细会 collection 根据类型指定的对象进行配置映射。
实际结果地图元素中的id元素可以使用 result 元素替代,只是用 id 可以提升性能,mybatis可以通过id元素配置的列的值判断唯一时间,如果我们使用 result 元素,那么判断是否是同一条记录的,需要通过所有都去判断了所以,通过 id 可以提升性能,使用id元素在对岸多中可以提升性能,在单表中使用id元素结果元素,性能还是一样的。
映射器接口
OrderModel getById(Integer id);
测试用例
com.javacode.chat05.demo3.Demo3Test#getById1
@Before
public void before() throws IOException {
//指定mybatis全局配置文件
String resource = "demo/mybatis-config.xml";
//读取全局配置文件
InputStream inputStream = Resources.getResourceAsStream(resource);
//构建SqlSessionFactory对象
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
this.sqlSessionFactory = sqlSessionFactory;
}
@Test
public void getById() {
try (SqlSession sqlSession = this.sqlSessionFactory.openSession(true);) {
OrderMapper mapper = sqlSession.getMapper(OrderMapper.class);
Integer id = ;
OrderModel orderModel = mapper.getById(id);
log.info("{}", orderModel);
}
}
运行输出
:52.092 [main] DEBUG c.j.c.d.mapper.OrderMapper.getById1 - ==> Preparing: SELECT a.id , a.user_id, a.create_time, a.up_time, b.id orderDetailId, b.order_id, b.goods_id, b.num, b.total_price FROM t_order a, t_order_detail b WHERE a.id = b.order_id AND a.id = ?
:52.124 [main] DEBUG c.j.c.d.mapper.OrderMapper.getById1 - ==> Parameters: 1(Integer)
:52.148 [main] DEBUG c.j.c.d.mapper.OrderMapper.getById1 - <== Total: 2
:52.148 [main] INFO c.j.chat05.demo3.Demo3Test - OrderModel(id=1, userId=2, createTime=1577947790, upTime=1577947790, orderDetailModelList=[OrderDetailModel(id=1, orderId=1, goodsId=1, num=2, totalPrice=17.76), OrderDetailModel(id=2, orderId=1, goodsId=1, num=1, totalPrice=16.66)])
注意一条输出,和期望的结果一致。
方式2
通过2次,然后对结果进行封装,先通过订单id然后查询的订单信息,然后通过订单id的订单明细列表,封装结果。mybatis中默认支持如此操作,还是通过 collection 元素来实现的。
订单明细映射器.xml
<select id="getListByOrderId" resultType="com.javacode2020.chat05.demo3.model.OrderDetailModel" parameterType="int">
<![CDATA[
SELECT
a.id,
a.order_id AS orderId,
a.goods_id AS goodsId,
a.num,
a.total_price AS totalPrice
FROM
t_order_detail a
WHERE
a.order_id = #{value}
]]>
</select>
订单映射器.xml
<resultMap id="orderModelMap" type="com.javacode2020.chat05.demo3.model.OrderModel">
<id column="id" property="id"/>
<result column="user_id" property="userId"/>
<result column="create_time" property="createTime"/>
<result column="up_time" property="upTime"/>
<collection property="orderDetailModelList" select="com.javacode.chat05.demo3.mapper.OrderDetailMapper.getListByOrderId1" column="id"/>
</resultMap>
<select id="getById" resultMap="orderModelMap2">
<![CDATA[
SELECT
a.id ,
a.user_id,
a.create_time,
a.up_time
FROM
t_order a
WHERE
a.id = #{value}
]]>
</select>
重点在下面这句配置:
<collection property="orderDetailModelList" select="com.javacode.chat05.demo3.mapper.OrderDetailMapper.getListByOrderId1" column="id"/>
orderDetailModelList 通过 select 属性指定的查询获取表示属性的值,即:
com.javacode.chat05.demo3.mapper.OrderDetailMapper.getListByOrderId1
查询参数是通过 column 属性指定的,这里使用 getById2 sql中的 id 作为条件,即订单id。
映射器接口
OrderModel getById(int id);
测试用例
com.javacode.chat05.demo3.Demo3Test#getById2
@Test
public void getById() {
try (SqlSession sqlSession = this.sqlSessionFactory.openSession(true);) {
OrderMapper mapper = sqlSession.getMapper(OrderMapper.class);
OrderModel orderModel = mapper.getById(1);
log.info("{}", orderModel);
}
}
运行输出
:07.087 [main] DEBUG c.j.c.d.mapper.OrderMapper.getById2 - ==> Preparing: SELECT a.id , a.user_id, a.create_time, a.up_time FROM t_order a WHERE a.id = ?
:07.117 [main] DEBUG c.j.c.d.mapper.OrderMapper.getById2 - ==> Parameters: 1(Integer)
:07.135 [main] DEBUG c.j.c.d.m.O.getListByOrderId1 - ====> Preparing: SELECT a.id, a.order_id AS orderId, a.goods_id AS goodsId, a.num, a.total_price AS totalPrice FROM t_order_detail a WHERE a.order_id = ?
:07.136 [main] DEBUG c.j.c.d.m.O.getListByOrderId1 - ====> Parameters: 1(Integer)
:07.141 [main] DEBUG c.j.c.d.m.O.getListByOrderId1 - <==== Total: 2
:07.142 [main] DEBUG c.j.c.d.mapper.OrderMapper.getById2 - <== Total: 1
:07.142 [main] INFO c.j.chat05.demo3.Demo3Test - OrderModel(id=1, userId=2, createTime=1577947790, upTime=1577947790, orderDetailModelList=[OrderDetailModel(id=1, orderId=1, goodsId=1, num=2, totalPrice=17.76), OrderDetailModel(id=2, orderId=1, goodsId=1, num=1, totalPrice=16.66)])
输出有2次,先通过订单id订单信息,然后通过订单id订单明细,mybatis内部对结果进行了整体查询查询。