MyBatis多对多关联查询

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

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

示例

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

1. 创建数据表

创建 order(订单),product(商品)和 order_details(订单和商品中间表),SQL 语句如下。
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 net.biancheng.po;

import java.util.List;

public class Order {
    private int oid;
    private int ordernum;
    private List<Product> products;

    /*省略setter和getter方法*/

    @Override
    public String toString() {
        return "Order [id=" + oid + ", ordernum=" + ordernum + ", products=" + products + "]";
    }

}
Product 类方法如下。
package net.biancheng.po;

import java.util.List;

public class Product {
    private int pid;
    private String name;
    private Double price;

    // 多对多中的一个一对多
    private List<Order> orders;

    /*省略setter和getter方法*/

    @Override
    public String toString() {
        return "Product [id=" + pid + ", name=" + name + ", price=" + price + "]";
    }
}

3. 创建接口和映射文件

OrderMapper 接口代码如下。
package net.biancheng.mapper;

import java.util.List;

import net.biancheng.po.Order;

public interface OrderMapper {
    public 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="net.biancheng.mapper.OrderMapper">

    <resultMap type="net.biancheng.po.Order" id="orderMap">
        <id property="oid" column="oid" />
        <result property="ordernum" column="ordernum" />

        <collection property="products"
            ofType="net.biancheng.po.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>

4. 创建测试类

测试类代码如下。
package net.biancheng.test;

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

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 net.biancheng.mapper.OrderMapper;
import net.biancheng.po.Order;

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

        List<Order> orderList = ss.getMapper(OrderMapper.class).selectAllOrdersAndProducts();
        for (Order or : orderList) {
            System.out.println(or);
        }
    }
}
运行结果如下。

DEBUG [main] - ==>  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`
DEBUG [main] - ==> Parameters:
DEBUG [main] - <==      Total: 6
Order [id=1, ordernum=20200107, products=[Product [id=1, name=Java教程, price=128.0], Product [id=2, name=C语言教程, price=138.0], Product [id=3, name=Python教程, price=132.35]]]
Order [id=2, ordernum=20200806, products=[Product [id=3, name=Python教程, price=132.35], Product [id=1, name=Java教程, price=128.0]]]
Order [id=3, ordernum=20206702, products=[Product [id=2, name=C语言教程, price=138.0]]]