MyBatis(四)MyBatis关联(级联)查询

MyBatis 目录

MyBatis关联(级联)查询

​ 级联关系是一个数据库实体的概念,有 3 种级联关系,分别是一对一级联、一对多级联以及多对多级联。例如,一个角色可以分配给多个用户,也可以只分配给一个用户。大部分场景下,我们都需要获取角色信息和用户信息,所以会经常遇见以下 SQL。s

SELECT r.*,u.* FROM t_role r
INNER JOIN t_user_role ur ON r.id = ur.id
INNER JOIN t_user u ON ur.user_id = u.id
WHERE r.id = #{id}

在级联中存在 3 种对应关系。

  • 一对多的关系,如角色和用户的关系。通俗的理解就是,一家软件公司会存在许多软件工程师,公司和软件工程师就是一对多的关系。
  • 一对一的关系。每个软件工程师都有一个编号(ID),这是他在公司的标识,它与工程师是一对一的关系。
  • 多对多的关系,有些公司一个角色可以对应多个用户,但是一个用户可以兼任多个角色。通俗的说,一个人既可以是总经理,同时也是技术总监,而技术总监这个职位可以对应多个人,这就是多对多的关系。

MyBatis一对一关联查询

一对一级联关系在现实生活中是十分常见的,例如一个大学生只有一个学号,一个学号只属于一个学生。同样,人与身份证也是一对一的级联关系。

在 MyBatis 中,通过 <resultMap> 元素的子元素 <association> 处理一对一级联关系。示例代码如下。

<association property="studentCard" column="cardId"
                     javaType="org.mybatis.example.StudentCard"
                     select="org.mybatis.example.StudentCardMapper.selectStuCardById" />

<association>元素中通常使用以下属性。

  • property:指定映射到实体类的对象属性。
  • column:指定表中对应的字段(即查询返回的列名)。
  • javaType:指定映射到实体对象属性的类型。
  • select:指定引入嵌套查询的子 SQL 语句,该属性用于关联映射中的嵌套查询。

一对一关联查询可采用以下两种方式:

  • 单步查询,通过关联查询实现
  • 分步查询,通过两次或多次查询,为一对一关系的实体 Bean 赋值

示例

下面以学生和学号为例讲解一对一关联查询的处理过程。

1.创建数据表

创建 student(学生)和 studentcard(学号)数据表,SQL 语句如下。

DROP TABLE IF EXISTS `studentcard`;
CREATE TABLE `studentcard` (
  `id` int(20) NOT NULL AUTO_INCREMENT,
  `studentId` int(20) DEFAULT NULL,
  `startDate` date DEFAULT NULL,
  `endDate` date DEFAULT NULL,
  PRIMARY KEY (`id`),
  KEY `studentId` (`studentId`)
) ENGINE=InnoDB AUTO_INCREMENT=8 DEFAULT CHARSET=utf8;
insert  into `studentcard`(`id`,`studentId`,`startDate`,`endDate`) values (1,20200311,'2021-03-01','2021-03-11'),(2,20200314,'2021-03-01','2021-03-11'),(3,20200709,'2021-03-01','2021-03-11'),(4,20200508,'2021-03-01','2021-03-11'),(5,20207820,'2021-03-01','2021-03-11');
CREATE TABLE `student` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `name` varchar(20) CHARACTER SET utf8 COLLATE utf8_unicode_ci DEFAULT NULL,
  `sex` tinyint(4) DEFAULT NULL,
  `cardId` int(20) DEFAULT NULL,
  PRIMARY KEY (`id`),
  KEY `cardId` (`cardId`),
  CONSTRAINT `student_ibfk_1` FOREIGN KEY (`cardId`) REFERENCES `studentcard` (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=7 DEFAULT CHARSET=utf8;
insert  into `student`(`id`,`name`,`sex`,`cardId`) values (1,'C语言中文网',0,1),(2,'编程帮',0,2),(3,'赵小红',1,3),(4,'李晓明',0,4),(5,'李紫薇',1,5),(6,'钱百百',0,NULL);

2. 创建持久化类

关于Lombok的介绍:Lombok介绍、使用方法和总结 - 猿人谷 - 博客园 (cnblogs.com)

在应用的org.mybatis.example包下创建数据表对应的持久化类 StudentStudentCard

package org.mybatis.example;

import lombok.Data;
import lombok.ToString;

@Data
@ToString
public class Student {
    private int id;
    private String name;
    private int sex;
    private StudentCard studentCard;
}

package org.mybatis.example;

import lombok.Data;
import lombok.ToString;

import java.util.Date;

@Data
@ToString
public class StudentCard {
    private int id;
    private int studentId;
    private Date startDate;
    private Date endDate;

}

3.分步查询

新建 StudentCardMapper 接口,代码如下。

package org.mybatis.example;

public interface StudentCardMapper {
    StudentCard selectStuCardById(int id);
}

resources->mapper新建 StudentCardMapper.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="org.mybatis.example.StudentCardMapper">
    <select id="selectStuCardById"
            resultType="org.mybatis.example.StudentCard">
        SELECT * FROM studentCard WHERE id = #{id}
    </select>
</mapper>

StudentMapper 接口方法代码如下。

package org.mybatis.example;

public interface StudentMapper {
    Student selectStuById1(int id);
    Student selectStuById2(int id);
}

StudentMapper.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="org.mybatis.example.StudentMapper">
    <!-- 一对一根据id查询学生信息:级联查询的第一种方法(嵌套查询,执行两个SQL语句) -->
    <resultMap type="org.mybatis.example.Student" id="cardAndStu1">
        <id property="id" column="id" />
        <result property="name" column="name" />
        <result property="sex" column="sex" />
        <!-- 一对一级联查询 -->
        <association property="studentCard" column="cardId"
                     javaType="org.mybatis.example.StudentCard"
                     select="org.mybatis.example.StudentCardMapper.selectStuCardById" />
    </resultMap>
    <select id="selectStuById1" parameterType="Integer"
            resultMap="cardAndStu1">
        select * from student where id=#{id}
    </select>
</mapper>

4. 创建配置文件

resources文件夹下新建 mybatis-config.xml

<?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>
    <environments default="development">
        <environment id="development">
            <transactionManager type="JDBC"/>
            <dataSource type="POOLED">
                <property name="driver" value="com.mysql.cj.jdbc.Driver"/>
                <property name="url" value="jdbc:mysql://localhost:3306/jdbc_test?characterEncoding=utf8"/>
                <property name="username" value="root"/>
                <property name="password" value="123456"/>
            </dataSource>
        </environment>
    </environments>
    <mappers>
        <mapper resource="mapper/StudentCardMapper.xml"/>
        <mapper resource="mapper/StudentMapper.xml"/>
    </mappers>
</configuration>

5.测试

MainApplication

package org.mybatis.example;

import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

import java.io.IOException;
import java.io.InputStream;

public class MainApplication {
    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();
        Student stu = ss.getMapper(StudentMapper.class).selectStuById1(2);
        System.out.println(stu);
    }
}

Student(id=2, name=编程帮, sex=0, studentCard=StudentCard(id=2, studentId=20200314, startDate=Mon Mar 01 00:00:00 CST 2021, endDate=Thu Mar 11 00:00:00 CST 2021))

6.打印sql

开启控制台sql语句打印的多种方式

在mybatis的配置文件中添加:

<settings>
    <!-- 打印sql日志 -->
    <setting name="logImpl" value="STDOUT_LOGGING" />
</settings>

mybatis的配置文件----mybatis-config.xml如下:

<?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>
    <settings>
        <!-- 打印sql日志 -->
        <setting name="logImpl" value="STDOUT_LOGGING" />
    </settings>
    <environments default="development">
        <environment id="development">
            <transactionManager type="JDBC"/>
            <dataSource type="POOLED">
                <property name="driver" value="com.mysql.cj.jdbc.Driver"/>
                <property name="url" value="jdbc:mysql://localhost:3306/jdbc_test?characterEncoding=utf8"/>
                <property name="username" value="root"/>
                <property name="password" value="123456"/>
            </dataSource>
        </environment>
    </environments>
    <mappers>
        <mapper resource="mapper/StudentCardMapper.xml"/>
        <mapper resource="mapper/StudentMapper.xml"/>
    </mappers>
</configuration>

运行输出如下

==>  Preparing: select * from student where id=?
==> Parameters: 2(Integer)
<==    Columns: id, name, sex, cardId
<==        Row: 2, 编程帮, 0, 2
====>  Preparing: SELECT * FROM studentCard WHERE id = ?
====> Parameters: 2(Integer)
<====    Columns: id, studentId, startDate, endDate
<====        Row: 2, 20200314, 2021-03-01, 2021-03-11
<====      Total: 1
<==      Total: 1
Student(id=2, name=编程帮, sex=0, studentCard=StudentCard(id=2, studentId=20200314, startDate=Mon Mar 01 00:00:00 CST 2021, endDate=Thu Mar 11 00:00:00 CST 2021))

由于我们使用的分布查询 所以执行了两次sql语句

7.单步查询

修改StudentMapper.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="org.mybatis.example.StudentMapper">
    <!-- 一对一根据id查询学生信息:级联查询的第一种方法(嵌套查询,执行两个SQL语句) -->
    <resultMap type="org.mybatis.example.Student" id="cardAndStu1">
        <id property="id" column="id" />
        <result property="name" column="name" />
        <result property="sex" column="sex" />
        <!-- 一对一级联查询 -->
        <association property="studentCard" javaType="org.mybatis.example.StudentCard">
            <id property="id" column="id" />
            <result property="studentId" column="studentId" />
        </association>
    </resultMap>
    <select id="selectStuById1" parameterType="Integer"
            resultMap="cardAndStu1">
       SELECT s.*,sc.studentId FROM student s,studentCard sc
    WHERE
        s.cardId = sc.id AND s.id=#{id}
    </select>
</mapper>

输出结果

==>  Preparing: SELECT s.*,sc.studentId FROM student s,studentCard sc WHERE s.cardId = sc.id AND s.id=?
==> Parameters: 2(Integer)
<==    Columns: id, name, sex, cardId, studentId
<==        Row: 2, 编程帮, 0, 2, 20200314
<==      Total: 1
Student(id=2, name=编程帮, sex=0, studentCard=StudentCard(id=2, studentId=20200314, startDate=null, endDate=null))

MyBatis一对多关联查询

在 MyBatis 中,通过 <resultMap> 元素的子元素 <collection> 处理一对多级联关系,collection 可以将关联查询的多条记录映射到一个 list 集合属性中。示例代码如下。

<collection property="orderList"
        ofType="net.biancheng.po.Order" column="id"
        select="net.biancheng.mapper.OrderMapper.selectOrderById" />

<collection>元素中通常使用以下属性。

  • property:指定映射到实体类的对象属性。
  • column:指定表中对应的字段(即查询返回的列名)。
  • javaType:指定映射到实体对象属性的类型。
  • select:指定引入嵌套查询的子 SQL 语句,该属性用于关联映射中的嵌套查询。

一对多关联查询可采用以下两种方式:

  • 分步查询,通过两次或多次查询,为一对多关系的实体 Bean 赋值
  • 单步查询,通过关联查询实现

示例

下面以用户和订单为例讲解一对多关联查询(实现“根据 id 查询用户及其关联的订单信息”的功能)的处理过程。

1. 创建数据表

本实例需要两张数据表,一张是用户表 user,一张是订单表 order,这两张表具有一对多的级联关系。SQL 语句如下:

DROP TABLE IF EXISTS `user`;
CREATE TABLE `user` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `name` varchar(20) DEFAULT NULL,
  `pwd` varchar(20) DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=7 DEFAULT CHARSET=utf8;
insert  into `user`(`id`,`name`,`pwd`) values (1,'编程帮','123'),(2,'C语言中文网','456'),(3,'赵小红','123'),(4,'李晓明','345'),(5,'杨小胤','123'),(6,'谷小乐','789');


CREATE TABLE `order` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `ordernum` int(25) DEFAULT NULL,
  `userId` int(11) DEFAULT NULL,
  PRIMARY KEY (`id`),
  KEY `userId` (`userId`),
  CONSTRAINT `order_ibfk_1` FOREIGN KEY (`userId`) REFERENCES `user` (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=9 DEFAULT CHARSET=utf8;
insert  into `order`(`id`,`ordernum`,`userId`) values (1,20200107,1),(2,20200806,2),(3,20206702,3),(4,20200645,1),(5,20200711,2),(6,20200811,2),(7,20201422,3),(8,20201688,4);

2. 创建持久化类

创建持久化类 User 和 Order,代码分别如下。

package org.mybatis.example;

import lombok.Data;
import lombok.ToString;

import java.util.List;

@Data
@ToString
public class User {
    private int id;
    private String name;
    private String pwd;
    private List<Order> orderList;
}

package org.mybatis.example;

import lombok.Data;
import lombok.ToString;

@Data
@ToString
public class Order {
    private int id;
    private int ordernum;
}

3.查询

分布查询

OrderMapper 接口代码如下

package org.mybatis.example;

import java.util.List;

public interface OrderMapper {
    List<Order> selectOrderById(int id);
}

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="org.mybatis.example.OrderMapper">
    <!-- 根据id查询订单信息 -->
    <select id="selectOrderById" resultType="org.mybatis.example.Order"
            parameterType="Integer">
        SELECT * FROM `order` where userId=#{id}
    </select>
</mapper>

UserMapper

package org.mybatis.example;

public interface UserMapper {
    User selectUserOrderById1(int id);
}

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="org.mybatis.example.UserMapper">
    <!-- 一对多 根据id查询用户及其关联的订单信息:级联查询的第一种方法(分步查询) -->
    <resultMap type="org.mybatis.example.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="org.mybatis.example.Order" column="id"
                    select="org.mybatis.example.OrderMapper.selectOrderById" />
    </resultMap>
    <select id="selectUserOrderById1" parameterType="Integer"
            resultMap="userAndOrder1">
        select * from user where id=#{id}
    </select>
</mapper>


在配置文件中添加mapper扫描

<mappers>
        <mapper resource="mapper/OrderMapper.xml"/>
        <mapper resource="mapper/UserMapper.xml"/>
    </mappers>

测试代码如下

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);
    }
}

输出

==>  Preparing: select * from user where id=?
==> Parameters: 1(Integer)
<==    Columns: id, name, pwd
<==        Row: 1, 编程帮, 123
====>  Preparing: SELECT * FROM `order` where userId=?
====> Parameters: 1(Integer)
<====    Columns: id, ordernum, userId
<====        Row: 1, 20200107, 1
<====        Row: 4, 20200645, 1
<====      Total: 2
<==      Total: 1
User(id=1, name=编程帮, pwd=123, orderList=[Order(id=1, ordernum=20200107), Order(id=4, ordernum=20200645)])

单步查询

该种方式实现一对多关联查询需要修改 Order 持久化类,因为 Order 中的 id 不能和 User 中的 id 重复。

package org.mybatis.example;

import lombok.Data;
import lombok.ToString;

@Data
@ToString
public class Order {
    private int oId;
    private int ordernum;
}

UserMapper 类代码如下。

User selectUserOrderById1(int id);

UserMapper.xml 中相关映射 SQL 语句如下。

<?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="org.mybatis.example.UserMapper">
    <!-- 一对多 根据id查询用户及其关联的订单信息:级联查询的第一种方法(分步查询) -->
    <resultMap type="org.mybatis.example.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="org.mybatis.example.Order">
            <id property="oId" column="oId" />
            <result property="ordernum" column="ordernum" />
        </collection>
    </resultMap>
    <select id="selectUserOrderById1" parameterType="Integer"
            resultMap="userAndOrder1">
        SELECT u.*,o.id as oId,o.ordernum FROM `user` u,`order` o
    WHERE
    u.id=o.`userId` AND u.id=#{id}
    </select>
</mapper>


测试运行如下

==>  Preparing: SELECT u.*,o.id as oId,o.ordernum FROM `user` u,`order` o WHERE u.id=o.`userId` AND u.id=?
==> Parameters: 1(Integer)
<==    Columns: id, name, pwd, oId, ordernum
<==        Row: 1, 编程帮, 123, 1, 20200107
<==        Row: 1, 编程帮, 123, 4, 20200645
<==      Total: 2
User(id=1, name=编程帮, pwd=123, orderList=[Order(oId=1, ordernum=20200107), Order(oId=4, ordernum=20200645)])

MyBatis多对多关联查询

实际应用中,由于多对多的关系比较复杂,会增加理解和关联的复杂度,所以应用较少。MyBatis 没有实现多对多级联,推荐通过两个一对多级联替换多对多级联,以降低关系的复杂度,简化程序。

例如,一个订单可以有多种商品,一种商品可以对应多个订单,订单与商品就是多对多的级联关系。可以使用一个中间表(订单记录表)将多对多级联转换成两个一对多的关系。

下面以订单和商品(实现“查询所有订单以及每个订单对应的商品信息”的功能)为例讲解多对多关联查询。

1. 创建数据表

创建 order(订单),product(商品)和 order_details(订单和商品中间表),SQL 语句如下。

DROP TABLE IF EXISTS `order`;
CREATE TABLE `order` (
  `oid` int(11) NOT NULL AUTO_INCREMENT,
  `ordernum` int(25) DEFAULT NULL,
  `userId` int(11) DEFAULT NULL,
  PRIMARY KEY (`oid`),
  KEY `userId` (`userId`),
  CONSTRAINT `order_ibfk_1` FOREIGN KEY (`userId`) REFERENCES `user` (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=10 DEFAULT CHARSET=utf8;
insert  into `order`(`oid`,`ordernum`,`userId`) values (1,20200107,1),(2,20200806,2),(3,20206702,3),(4,20200645,1),(5,20200711,2),(6,20200811,2),(7,20201422,3),(8,20201688,4),(9,NULL,5);
DROP TABLE IF EXISTS `orders_detail`;
CREATE TABLE `orders_detail` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `orderId` int(11) DEFAULT NULL,
  `productId` int(11) DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=7 DEFAULT CHARSET=utf8;
insert  into `orders_detail`(`id`,`orderId`,`productId`) values (1,1,1),(2,1,2),(3,1,3),(4,2,3),(5,2,1),(6,3,2);
DROP TABLE IF EXISTS `product`;
CREATE TABLE `product` (
  `pid` int(11) NOT NULL AUTO_INCREMENT,
  `name` varchar(25) DEFAULT NULL,
  `price` double DEFAULT NULL,
  PRIMARY KEY (`pid`)
) ENGINE=InnoDB AUTO_INCREMENT=5 DEFAULT CHARSET=utf8;
insert  into `product`(`pid`,`name`,`price`) values (1,'Java教程',128),(2,'C语言教程',138),(3,'Python教程',132.35);

2.创建持久化类

Order 类代码如下。

package org.mybatis.example;

import lombok.Data;
import lombok.ToString;

import java.util.List;

@Data
@ToString
public class Order {
    private int oid;
    private int ordernum;
    private List<Product> products;
}

Product 类方法如下。

package org.mybatis.example;

import lombok.Data;
import lombok.ToString;

import java.util.List;

@Data
@ToString
public class Product {
    private int pid;
    private String name;
    private Double price;
    // 多对多中的一个一对多
    private List<Order> orders;
}

3.创建接口和映射文件

OrderMapper 接口代码如下。

package org.mybatis.example;

import java.util.List;

public interface OrderMapper {
    List<Order> selectAllOrdersAndProducts();
}

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="org.mybatis.example.OrderMapper">

    <resultMap type="org.mybatis.example.Order" id="orderMap">
        <id property="oid" column="oid" />
        <result property="ordernum" column="ordernum" />

        <collection property="products"
                    ofType="org.mybatis.example.Product">
            <id property="pid" column="pid" />
            <result property="name" column="name" />
            <result property="price" column="price" />
        </collection>
    </resultMap>

    <select id="selectAllOrdersAndProducts" parameterType="Integer"
            resultMap="orderMap">
        SELECT o.oid,o.`ordernum`,p.`pid`,p.`name`,p.`price` FROM
        `order` o
        INNER JOIN orders_detail od ON o.oid=od.`orderId`
        INNER JOIN
        product p
        ON p.pid = od.`productId`
    </select>

</mapper>

配置文件添加

<mapper resource="mapper/OrderMapper.xml"/>

4. 测试

package org.mybatis.example;

import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

import java.io.IOException;
import java.io.InputStream;
import java.util.List;

public class MainApplication {
    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();
        List<Order> orderList = ss.getMapper(OrderMapper.class).selectAllOrdersAndProducts();
        for (Order or : orderList) {
            System.out.println(or);
        }
    }
}

输出如下

==>  Preparing: SELECT o.oid,o.`ordernum`,p.`pid`,p.`name`,p.`price` FROM `order` o INNER JOIN orders_detail od ON o.oid=od.`orderId` INNER JOIN product p ON p.pid = od.`productId`
==> Parameters: 
<==    Columns: oid, ordernum, pid, name, price
<==        Row: 1, 20200107, 1, Java教程, 128.0
<==        Row: 1, 20200107, 2, C语言教程, 138.0
<==        Row: 1, 20200107, 3, Python教程, 132.35
<==        Row: 2, 20200806, 3, Python教程, 132.35
<==        Row: 2, 20200806, 1, Java教程, 128.0
<==        Row: 3, 20206702, 2, C语言教程, 138.0
<==      Total: 6
Order(oid=1, ordernum=20200107, products=[Product(pid=1, name=Java教程, price=128.0, orders=null), Product(pid=2, name=C语言教程, price=138.0, orders=null), Product(pid=3, name=Python教程, price=132.35, orders=null)])
Order(oid=2, ordernum=20200806, products=[Product(pid=3, name=Python教程, price=132.35, orders=null), Product(pid=1, name=Java教程, price=128.0, orders=null)])
Order(oid=3, ordernum=20206702, products=[Product(pid=2, name=C语言教程, price=138.0, orders=null)])

Process finished with exit code 0

posted @ 2021-12-17 16:44  青杉  阅读(1329)  评论(0编辑  收藏  举报