(七)MyBatis從入門到入土——花式查詢

這是mybatis系列第7篇。沒看前文的建議先去【Java冢狐】公衆號中查看前文,方便理解和掌握。上一篇中咱們講述了一些關於獲取主鍵的方法,這篇文章中咱們將會更加深刻的介紹一些查詢的方法,特別是多表查詢。java

在開始以前先開始諸如建庫建表等準備工做。spring

建庫建表

建立一個db:mybatisdemosql

4張表:編程

  • user(用戶表)
  • goods(商品表)
  • orders(訂單表)
  • order_detail(訂單明細表)

表之間的關係:mybatis

  • orders和user是一對一的關係,一條訂單關聯一個用戶記錄
  • orders和order_detail是一對多關係,每一個訂單中可能包含多個子訂單,每一個子訂單對應一個商品

具體的建表語句以下所示:app

DROP DATABASE IF EXISTS `mybatisdemo`;
CREATE DATABASE `mybatisdemo`;
USE `mybatisdemo`;
DROP TABLE IF EXISTS user;
CREATE TABLE user(
  id int AUTO_INCREMENT PRIMARY KEY COMMENT '用戶id',
  name VARCHAR(32) NOT NULL DEFAULT '' COMMENT '用戶名'
) COMMENT '用戶表';
INSERT INTO user VALUES (1,'冢狐'),(2,'Java冢狐');
DROP TABLE IF EXISTS goods;
CREATE TABLE goods(
  id int AUTO_INCREMENT PRIMARY KEY COMMENT '商品id',
  name VARCHAR(32) NOT NULL DEFAULT '' COMMENT '商品名稱',
  price DECIMAL(10,2) NOT NULL DEFAULT 0 COMMENT '商品價格'
) COMMENT '商品信息表';
INSERT INTO goods VALUES (1,'Mybatis系列',8.00),(2,'spring系列',16.00);
DROP TABLE IF EXISTS orders;
CREATE TABLE orders(
  id int AUTO_INCREMENT PRIMARY KEY COMMENT '訂單id',
  user_id INT NOT NULL DEFAULT 0 COMMENT '用戶id,來源於user.id',
  create_time BIGINT NOT NULL DEFAULT 0 COMMENT '訂單建立時間(時間戳,秒)',
  up_time BIGINT NOT NULL DEFAULT 0 COMMENT '訂單最後修改時間(時間戳,秒)'
) COMMENT '訂單表';
INSERT INTO orders VALUES (1,2,unix_timestamp(now()),unix_timestamp(now())),(2,1,unix_timestamp(now()),unix_timestamp(now()));
DROP TABLE IF EXISTS order_detail;
CREATE TABLE order_detail(
  id int AUTO_INCREMENT PRIMARY KEY COMMENT '訂單明細id',
  order_id INT NOT NULL DEFAULT 0 COMMENT '訂單id,來源於order.id',
  goods_id INT NOT NULL DEFAULT 0 COMMENT '商品id,來源於goods.id',
  num INT NOT NULL DEFAULT 0 COMMENT '商品數量',
  total_price DECIMAL(12,2) NOT NULL DEFAULT 0 COMMENT '商品總金額'
) COMMENT '訂單表';
INSERT INTO order_detail VALUES (1,1,1,2,16.00),(2,1,1,1,16.00),(3,2,1,1,8.00);
select * from user;
select * from goods;
select * from orders;
select * from order_detail;

建好庫和表後,下一步咱們就開始咱們的查詢之旅,先從最基礎的單表查詢看起,依次介紹單表查詢、一對一查詢和一對多查詢。性能

單表查詢(3種方式)

先來介紹的就是單表查詢。測試

需求

須要按照訂單id查詢訂單信息。ui

方式1

建立每一個表對應的Model

db中表的字段是採用下劃線分割的,model中咱們是採用駱駝命名法來命名的,如OrderModel:this

package com.zhonghu.chat07.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;
}

其餘幾個Model也相似。

Mapper xml
<select id="getById" resultType="com.zhonghu.chat07.demo1.model.OrderModel">
    <![CDATA[
    SELECT a.id,a.user_id as userId,a.create_time createTime,a.up_time upTime FROM orders a WHERE a.id = #{value}
    ]]>
</select>

注意上面的resultType,標識結果的類型。

Mapper接口方法
OrderModel getById(int id);
mybatis全局配置文件
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configuration
        PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
    <!-- 引入外部jdbc配置 -->
    <properties resource="jdbc.properties"/>
    <!-- 環境配置,能夠配置多個環境 -->
    <environments default="demo4">
        <environment id="demo4">
            <!-- 事務管理器工廠配置 -->
            <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="demo1/mapper/UserMapper.xml" />
        <mapper resource="demo1/mapper/GoodsMapper.xml" />
        <mapper resource="demo1/mapper/OrderMapper.xml" />
        <mapper resource="demo1/mapper/OrderDetailMapper.xml" />
    </mappers>
</configuration>
測試用例
com.zhonghu.chat07.demo1.Demo1Test#getById
@Before
public void before() throws IOException {
    //指定mybatis全局配置文件
    String resource = "demo1/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);
    }
}
運行輸出
35: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 orders a WHERE a.id = ? 
35:59.239 [main] DEBUG c.j.c.d.mapper.OrderMapper.getById - ==> Parameters: 1(Integer)
35:59.258 [main] DEBUG c.j.c.d.mapper.OrderMapper.getById - <==      Total: 1
35:59.258 [main] INFO  c.j.chat05.demo1.Demo1Test - OrderModel(id=1, userId=2, createTime=1610803573, upTime=1610803573)
原理

sql中咱們使用了別名,將orders中的字段轉換成了和OrderModel中字段同樣的名稱,最後mybatis內部會經過反射,將查詢結果按照名稱到OrderModel中查找同名的字段,而後進行賦值。

方式2

若咱們項目中表對應的Model中的字段都是採用駱駝命名法,mybatis中能夠進行一些配置,可使表中的字段和對應Model中駱駝命名法的字段進行自動映射。

須要在mybatis全局配置文件中加入下面配置:

<settings>
    <!-- 是否開啓自動駝峯命名規則映射,及從xx_yy映射到xxYy -->
    <setting name="mapUnderscoreToCamelCase" value="true"/>
</settings>
Mapper xml
<select id="getById1" resultType="com.zhonghu.chat07.demo1.model.OrderModel">
    <![CDATA[
    SELECT a.id,a.user_id,a.create_time,a.up_time FROM orders a WHERE a.id = #{value}
    ]]>
</select>

注意上面的sql,咱們沒有寫別名了,因爲咱們開啓了自動駱駝命名映射,因此查詢結果會按照下面的關係進行自動映射:

sql對應的字段 OrderModel中的字段
id id
user_id userId
create_time createTime
up_time upTime
Mapper接口
OrderModel getById1(int id);
測試用例
com.zhonghu.chat05.demo1.Demo1Test#getById1
@Test
public void getById1() {
    try (SqlSession sqlSession = this.sqlSessionFactory.openSession(true);) {
        OrderMapper mapper = sqlSession.getMapper(OrderMapper.class);
        OrderModel orderModel = mapper.getById1(1);
        log.info("{}", orderModel);
    }
}
運行輸出
59: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 orders a WHERE a.id = ? 
59:44.917 [main] DEBUG c.j.c.d.mapper.OrderMapper.getById1 - ==> Parameters: 1(Integer)
59:44.935 [main] DEBUG c.j.c.d.mapper.OrderMapper.getById1 - <==      Total: 1
59:44.935 [main] INFO  c.j.chat05.demo1.Demo1Test - OrderModel(id=1, userId=2, createTime=1610803573, upTime=1610803573)

輸出中能夠看出,sql中的字段是下劃線的方式,OrderModel中的字段是駱駝命名法,結果也自動裝配成功,這個就是開啓mapUnderscoreToCamelCase產生的效果。

方式3

mapper xml中有個更強大的元素resultMap,經過這個元素能夠定義查詢結果的映射關係。

Mapper xml
<resultMap id="orderModelMap2" type="com.zhonghu.chat07.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="getById2" resultMap="orderModelMap2">
    <![CDATA[
    SELECT a.id,a.user_id,a.create_time,a.up_time FROM orders a WHERE a.id = #{value}
    ]]>
</select>

上面resultMap有2個元素須要指定:

  • id:resultMap標識
  • type:將結果封裝成什麼類型,此處咱們須要將結果分裝爲OrderModel

注意上面的select元素,有個resultMap,標識查詢結果使用哪一個resultMap進行映射,此處咱們使用的是orderModelMap2,因此查詢結果會按照orderModelMap2關聯的resultMap進行映射。

Mapper接口
OrderModel getById2(int id);
測試用例
com.zhonghu.chat07.demo1.Demo1Test#getById2
@Test
public void getById2() {
    try (SqlSession sqlSession = this.sqlSessionFactory.openSession(true);) {
        OrderMapper mapper = sqlSession.getMapper(OrderMapper.class);
        OrderModel orderModel = mapper.getById2(1);
        log.info("{}", orderModel);
    }
}

運行輸出

14: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 orders a WHERE a.id = ? 
14:12.546 [main] DEBUG c.j.c.d.mapper.OrderMapper.getById2 - ==> Parameters: 1(Integer)
14:12.564 [main] DEBUG c.j.c.d.mapper.OrderMapper.getById2 - <==      Total: 1
14:12.564 [main] INFO  c.j.chat05.demo1.Demo1Test - OrderModel(id=1, userId=2, createTime=1610803573, upTime=1610803573)

一對一關聯查詢(4種方式)

講完了單表查詢,下面開始連表查詢,首先就是一對一的查詢

需求

經過訂單id查詢訂單的時候,將訂單關聯的用戶信息也返回。

咱們修改一下OrderModel代碼,內部添加一個UserModel,以下:

package com.zhonghu.chat07.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;
}

UserModel內容:

package com.zhonghu.chat07.demo2.model;
import lombok.*;
@Getter
@Setter
@Builder
@ToString
@NoArgsConstructor
@AllArgsConstructor
public class UserModel {
    private Integer id;
    private String name;
}

方式1

Mapper xml
<resultMap id="orderModelMap1" type="com.zhonghu.chat07.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="getById1" resultMap="orderModelMap1">
    <![CDATA[
    SELECT
        a.id,
        a.user_id,
        a.create_time,
        a.up_time,
        b.name
    FROM
        orders a,
        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"/>

這個地方使用到了級聯賦值,多級之間用.進行引用,此處咱們只有一級,能夠有不少級。

Mapper 接口
OrderModel getById1(int id);
測試用例
com.zhonghu.chat07.demo2.Demo2Test#getById1
@Before
public void before() throws IOException {
    //指定mybatis全局配置文件
    String resource = "demo2/mybatis-config.xml";
    //讀取全局配置文件
    InputStream inputStream = Resources.getResourceAsStream(resource);
    //構建SqlSessionFactory對象
    SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
    this.sqlSessionFactory = sqlSessionFactory;
}
@Test
public void getById1() {
    try (SqlSession sqlSession = this.sqlSessionFactory.openSession(true);) {
        OrderMapper mapper = sqlSession.getMapper(OrderMapper.class);
        OrderModel orderModel = mapper.getById1(1);
        log.info("{}", orderModel);
    }
}
運行輸出
24: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 orders a, user b WHERE a.user_id = b.id AND a.id = ? 
24:20.843 [main] DEBUG c.j.c.d.mapper.OrderMapper.getById1 - ==> Parameters: 1(Integer)
24:20.861 [main] DEBUG c.j.c.d.mapper.OrderMapper.getById1 - <==      Total: 1
24:20.861 [main] INFO  c.j.chat05.demo2.Demo2Test - OrderModel(id=1, userId=2, createTime=1610803573, upTime=1610803573, userModel=UserModel(id=2, name=Java冢狐))

方式2

此次咱們須要使用mapper xml中另一個元素association,這個元素能夠配置關聯對象的映射關係,看示例。

Mapper xml
<resultMap id="orderModelMap2" type="com.zhonghu.chat07.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="getById2" resultMap="orderModelMap2">
    <![CDATA[
    SELECT
        a.id,
        a.user_id,
        a.create_time,
        a.up_time,
        b.name
    FROM
        orders a,
        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進行映射。

Mapper接口
OrderModel getById2(int id);
測試用例
@Test
public void getById2() {
    try (SqlSession sqlSession = this.sqlSessionFactory.openSession(true);) {
        OrderMapper mapper = sqlSession.getMapper(OrderMapper.class);
        OrderModel orderModel = mapper.getById2(1);
        log.info("{}", orderModel);
    }
}
運行結果
51: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 orders a, user b WHERE a.user_id = b.id AND a.id = ? 
51:44.925 [main] DEBUG c.j.c.d.mapper.OrderMapper.getById2 - ==> Parameters: 1(Integer)
51:44.941 [main] DEBUG c.j.c.d.mapper.OrderMapper.getById2 - <==      Total: 1
51:44.942 [main] INFO  c.j.chat05.demo2.Demo2Test - OrderModel(id=1, userId=2, createTime=1610803573, upTime=1610803573, userModel=UserModel(id=2, name=Java冢狐))

從結果的最後一行能夠看出,全部字段的值映射都是ok的。

方式3

先按照訂單id查詢訂單數據,而後在經過訂單中user_id去用戶表查詢用戶數據,經過兩次查詢,組合成目標結果,mybatis已經內置了這種操做,以下。

UserMapper.xml

咱們先定義一個經過用戶id查詢用戶信息的select元素,以下

<select id="getById" resultType="com.zhonghu.chat07.demo2.model.UserModel">
    <![CDATA[
    SELECT id,name FROM user where id = #{value}
    ]]>
</select>
OrderModel.xml
<resultMap id="orderModelMap3" type="com.zhonghu.chat07.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.zhonghu.chat07.demo2.mapper.UserMapper.getById" column="user_id" />
</resultMap>
<select id="getById3" resultMap="orderModelMap3">
    <![CDATA[
    SELECT
        a.id,
        a.user_id,
        a.create_time,
        a.up_time
    FROM
        orders a
    WHERE
        a.id = #{value}
    ]]>
</select>

OrderModel.userModel屬性的值來在於另一個查詢,這個查詢是經過association元素的select屬性指定的,此處使用的是

com.zhonghu.chat07.demo2.mapper.UserMapper.getById

這個查詢是有條件的,條件經過association的column進行傳遞的,此處傳遞的是getById3查詢結果中的user_id字段。

Mapper接口
OrderModel getById3(int id);
測試用例
com.zhonghu.chat07.demo2.Demo2Test#getById3
@Test
public void getById3() {
    try (SqlSession sqlSession = this.sqlSessionFactory.openSession(true);) {
        OrderMapper mapper = sqlSession.getMapper(OrderMapper.class);
        OrderModel orderModel = mapper.getById3(1);
        log.info("{}", orderModel);
    }
}
運行輸出
07: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 orders a WHERE a.id = ? 
07:12.600 [main] DEBUG c.j.c.d.mapper.OrderMapper.getById3 - ==> Parameters: 1(Integer)
07:12.619 [main] DEBUG c.j.c.d.mapper.UserMapper.getById - ====>  Preparing: SELECT id,name FROM user where id = ? 
07:12.620 [main] DEBUG c.j.c.d.mapper.UserMapper.getById - ====> Parameters: 2(Integer)
07:12.625 [main] DEBUG c.j.c.d.mapper.UserMapper.getById - <====      Total: 1
07:12.625 [main] DEBUG c.j.c.d.mapper.OrderMapper.getById3 - <==      Total: 1
07:12.625 [main] INFO  c.j.chat05.demo2.Demo2Test - OrderModel(id=1, userId=2, createTime=1610803573, upTime=1610803573, userModel=UserModel(id=2, name=Java冢狐))

從輸出中能夠看出有2次查詢,先按照訂單id查詢訂單,而後經過訂單記錄中用戶id去用戶表查詢用戶信息,最終執行了2次查詢。

方式4

方式3中給第二個查詢傳遞了一個參數,若是須要給第二個查詢傳遞多個參數怎麼辦呢?能夠這麼寫

<association property="屬性" select="查詢對應的select的id" column="{key1=父查詢字段1,key2=父查詢字段2,key3=父查詢字段3}" />

這種至關於給子查詢傳遞了一個map,子查詢中 須要用過map的key獲取對應的條件,看案例:

OrderMapper.xml

<resultMap id="orderModelMap4" type="com.zhonghu.chat07.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.zhonghu.chat07.demo2.mapper.UserMapper.getById1" column="{uid1=user_id,uid2=create_time}" />
</resultMap>
<select id="getById4" resultMap="orderModelMap4">
    <![CDATA[
    SELECT
        a.id,
        a.user_id,
        a.create_time,
        a.up_time
    FROM
        orders a
    WHERE
        a.id = #{value}
    ]]>
</select>

UserMapper.xml

<select id="getById1" resultType="com.zhonghu.chat07.demo2.model.UserModel">
    <![CDATA[
    SELECT id,name FROM user where id = #{uid1} and id = #{uid2}
    ]]>
</select>

Mapper接口

OrderModel getById4(int id);

測試用例

com.zhonghu.chat07.demo2.Demo2Test#getById4
@Test
public void getById4() {
    try (SqlSession sqlSession = this.sqlSessionFactory.openSession(true);) {
        OrderMapper mapper = sqlSession.getMapper(OrderMapper.class);
        OrderModel orderModel = mapper.getById4(1);
        log.info("{}", orderModel);
    }
}

運行輸出

19: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 orders a WHERE a.id = ? 
19:59.914 [main] DEBUG c.j.c.d.mapper.OrderMapper.getById4 - ==> Parameters: 1(Integer)
19:59.934 [main] DEBUG c.j.c.d.mapper.UserMapper.getById1 - ====>  Preparing: SELECT id,name FROM user where id = ? and id = ? 
19:59.934 [main] DEBUG c.j.c.d.mapper.UserMapper.getById1 - ====> Parameters: 2(Integer), 1610803573(Long)
19:59.939 [main] DEBUG c.j.c.d.mapper.UserMapper.getById1 - <====      Total: 0
19:59.939 [main] DEBUG c.j.c.d.mapper.OrderMapper.getById4 - <==      Total: 1
19:59.939 [main] INFO  c.j.chat05.demo2.Demo2Test - OrderModel(id=1, userId=2, createTime=1610803573, upTime=1610803573, userModel=null)

輸出中看一下第二個查詢的條件,傳過來的是第一個查詢的user_id和create_time。

一對多查詢(2種方式)

最後就是進行一隊多查詢的解析

需求

根據訂單id查詢出訂單信息,而且查詢出訂單明細列表。

先修改一下OrderModel代碼,以下:

package com.zhonghu.chat07.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;
}

OrderModel中添加了一個集合orderDetailModelList用來存放訂單詳情列表。

方式1

OrderMapper.xml
<resultMap id="orderModelMap1" type="com.zhonghu.chat07.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.zhonghu.chat07.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="getById1" 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
        orders a,
        order_detail b
    WHERE
        a.id = b.order_id
        AND a.id = #{value}
    ]]>
</select>

注意上面的getById1中的sql,這個sql中使用到了t_order和t_order_detail鏈接查詢,這個查詢會返回多條結果,可是最後結果按照orderModelMap1進行映射,最後只會返回一個OrderModel對象,關鍵在於collection元素,這個元素用來定義集合中元素的映射關係,有2個屬性須要注意:

  • property:對應的屬性名稱
  • ofType:集合中元素的類型,此處是OrderDetailModel

原理是這樣的,注意orderModelMap1中有個

<id column="id" property="id"/>

查詢出來的結果會按照這個配置中指定的column進行分組,即按照訂單id進行分組,每一個訂單對應多個訂單明細,訂單明細會按照collection的配置映射爲ofType元素指定的對象。

實際resultMap元素中的id元素可使用result元素代替,只是用id能夠提高性能,mybatis能夠經過id元素配置的列的值判斷惟一一條記錄,若是咱們使用result元素,那麼判斷是不是同一條記錄的時候,須要經過全部列去判斷了,因此經過id能夠提高性能,使用id元素在一對多中能夠提高性能,在單表查詢中使用id元素仍是result元素,性能都是同樣的。

Mapper接口
OrderModel getById1(Integer id);
測試用例
com.zhonghu.chat07.demo3.Demo3Test#getById1
@Before
public void before() throws IOException {
    //指定mybatis全局配置文件
    String resource = "demo3/mybatis-config.xml";
    //讀取全局配置文件
    InputStream inputStream = Resources.getResourceAsStream(resource);
    //構建SqlSessionFactory對象
    SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
    this.sqlSessionFactory = sqlSessionFactory;
}
@Test
public void getById1() {
    try (SqlSession sqlSession = this.sqlSessionFactory.openSession(true);) {
        OrderMapper mapper = sqlSession.getMapper(OrderMapper.class);
        Integer id = 1;
        OrderModel orderModel = mapper.getById1(id);
        log.info("{}", orderModel);
    }
}
運行輸出
03: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 orders a, order_detail b WHERE a.id = b.order_id AND a.id = ? 
03:52.124 [main] DEBUG c.j.c.d.mapper.OrderMapper.getById1 - ==> Parameters: 1(Integer)
03:52.148 [main] DEBUG c.j.c.d.mapper.OrderMapper.getById1 - <==      Total: 2
03:52.148 [main] INFO  c.j.chat05.demo3.Demo3Test - OrderModel(id=1, userId=2, createTime=1610803573, upTime=1610803573, orderDetailModelList=[OrderDetailModel(id=1, orderId=1, goodsId=1, num=2, totalPrice=16.00), OrderDetailModel(id=2, orderId=1, goodsId=1, num=1, totalPrice=16.00)])

注意最後一條輸出,和指望的結果一致。

方式2

經過2次查詢,而後對結果進行分裝,先經過訂單id查詢訂單信息,而後經過訂單id查詢訂單明細列表,而後封裝結果。mybatis中默認支持這麼玩,仍是經過collection元素來實現的。

OrderDetailMapper.xml
<select id="getListByOrderId1" resultType="com.zhonghu.chat07.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
        order_detail a
    WHERE
        a.order_id = #{value}
    ]]>
</select>
OrderMapper.xml
<resultMap id="orderModelMap2" type="com.zhonghu.chat07.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.zhonghu.chat07.demo3.mapper.OrderDetailMapper.getListByOrderId1" column="id"/>
</resultMap>
<select id="getById2" resultMap="orderModelMap2">
    <![CDATA[
    SELECT
        a.id ,
        a.user_id,
        a.create_time,
        a.up_time
    FROM
        orders a
    WHERE
        a.id = #{value}
    ]]>
</select>

重點在於下面這句配置:

<collection property="orderDetailModelList" select="com.zhonghu.chat07.demo3.mapper.OrderDetailMapper.getListByOrderId1" column="id"/>

表示orderDetailModelList屬性的值經過select屬性指定的查詢獲取,即:

com.zhonghu.chat07.demo3.mapper.OrderDetailMapper.getListByOrderId1

查詢參數是經過column屬性指定的,此處使用getById2 sql中的id做爲條件,即訂單id。

Mapper接口
OrderModel getById2(int id);
測試用例
com.zhonghu.chat07.demo3.Demo3Test#getById2
@Test
public void getById2() {
    try (SqlSession sqlSession = this.sqlSessionFactory.openSession(true);) {
        OrderMapper mapper = sqlSession.getMapper(OrderMapper.class);
        OrderModel orderModel = mapper.getById2(1);
        log.info("{}", orderModel);
    }
}
運行輸出
10: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 ordera a WHERE a.id = ? 
10:07.117 [main] DEBUG c.j.c.d.mapper.OrderMapper.getById2 - ==> Parameters: 1(Integer)
10: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 order_detail a WHERE a.order_id = ? 
10:07.136 [main] DEBUG c.j.c.d.m.O.getListByOrderId1 - ====> Parameters: 1(Integer)
10:07.141 [main] DEBUG c.j.c.d.m.O.getListByOrderId1 - <====      Total: 2
10:07.142 [main] DEBUG c.j.c.d.mapper.OrderMapper.getById2 - <==      Total: 1
10:07.142 [main] INFO  c.j.chat05.demo3.Demo3Test - OrderModel(id=1, userId=2, createTime=1610803573, upTime=1610803573, orderDetailModelList=[OrderDetailModel(id=1, orderId=1, goodsId=1, num=2, totalPrice=16.00), OrderDetailModel(id=2, orderId=1, goodsId=1, num=1, totalPrice=16.00)])

輸出中有2次查詢,先經過訂單id查詢訂單信息,而後經過訂單id查詢訂單明細,mybatis內部對結果進行了組裝。

總結

  1. mybatis全局配置文件中經過mapUnderscoreToCamelCase能夠開啓sql中的字段和javabean中的駱駝命名法的字段進行自動映射
  2. 掌握resultMap元素常見的用法
  3. 一對一關聯查詢使用resultMap->association元素(2種方式)
  4. 一對多查詢使用resultMap->collection元素(2種方式)
  5. resultMap中使用id元素主要在複雜的關聯查詢中能夠提高效率,能夠經過這個來判斷記錄的惟一性,若是沒有這個,須要經過全部的result相關的列才能判斷記錄的惟一性

建議

mybatis爲咱們提供了強大的關聯查詢,不過我的建議儘可能少用,最好是採用單表的方式查詢,在程序中經過屢次查詢,而後本身對結果進行組裝。

Model中最好只定義一些和單表字段關聯的屬性,不要摻雜着其餘對象的引用。

最後

  • 若是以爲看完有收穫,但願能關注一下,順便給我點個贊,這將會是我更新的最大動力,感謝各位的支持
  • 歡迎各位關注個人公衆號【java冢狐】,專一於java和計算機基礎知識,保證讓你看完有所收穫,不信你打我
  • 求一鍵三連:點贊、轉發、在看。
  • 若是看完有不一樣的意見或者建議,歡迎多多評論一塊兒交流。感謝各位的支持以及厚愛。

——我是冢狐,和你同樣熱愛編程。

歡迎關注公衆號「Java冢狐」獲取最新消息

相關文章
相關標籤/搜索