MyBatis多对多关联查询

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

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

示例

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

1. 创建数据表

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

  1. CREATE TABLE `order` (
  2. `oid` int(11) NOT NULL AUTO_INCREMENT,
  3. `ordernum` int(25) DEFAULT NULL,
  4. `userId` int(11) DEFAULT NULL,
  5. PRIMARY KEY (`oid`),
  6. KEY `userId` (`userId`),
  7. CONSTRAINT `order_ibfk_1` FOREIGN KEY (`userId`) REFERENCES `user` (`id`)
  8. ) ENGINE=InnoDB AUTO_INCREMENT=10 DEFAULT CHARSET=utf8;
  9. 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);
  10. DROP TABLE IF EXISTS `orders_detail`;
  11. CREATE TABLE `orders_detail` (
  12. `id` int(11) NOT NULL AUTO_INCREMENT,
  13. `orderId` int(11) DEFAULT NULL,
  14. `productId` int(11) DEFAULT NULL,
  15. PRIMARY KEY (`id`)
  16. ) ENGINE=InnoDB AUTO_INCREMENT=7 DEFAULT CHARSET=utf8;
  17. 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);
  18. DROP TABLE IF EXISTS `product`;
  19. CREATE TABLE `product` (
  20. `pid` int(11) NOT NULL AUTO_INCREMENT,
  21. `name` varchar(25) DEFAULT NULL,
  22. `price` double DEFAULT NULL,
  23. PRIMARY KEY (`pid`)
  24. ) ENGINE=InnoDB AUTO_INCREMENT=5 DEFAULT CHARSET=utf8;
  25. insert into `product`(`pid`,`name`,`price`) values (1,'Java教程',128),(2,'C语言教程',138),(3,'Python教程',132.35);

2. 创建持久化类

Order 类代码如下。

  1. package net.biancheng.po;
  2. import java.util.List;
  3. public class Order {
  4. private int oid;
  5. private int ordernum;
  6. private List<Product> products;
  7. /*省略setter和getter方法*/
  8. @Override
  9. public String toString() {
  10. return "Order [id=" + oid + ", ordernum=" + ordernum + ", products=" + products + "]";
  11. }
  12. }

Product 类方法如下。

  1. package net.biancheng.po;
  2. import java.util.List;
  3. public class Product {
  4. private int pid;
  5. private String name;
  6. private Double price;
  7. // 多对多中的一个一对多
  8. private List<Order> orders;
  9. /*省略setter和getter方法*/
  10. @Override
  11. public String toString() {
  12. return "Product [id=" + pid + ", name=" + name + ", price=" + price + "]";
  13. }
  14. }

3. 创建接口和映射文件

OrderMapper 接口代码如下。

  1. package net.biancheng.mapper;
  2. import java.util.List;
  3. import net.biancheng.po.Order;
  4. public interface OrderMapper {
  5. public List<Order> selectAllOrdersAndProducts();
  6. }

OrderMapper.xml 代码如下。

  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <!DOCTYPE mapper
  3. PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
  4. "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
  5. <mapper namespace="net.biancheng.mapper.OrderMapper">
  6. <resultMap type="net.biancheng.po.Order" id="orderMap">
  7. <id property="oid" column="oid" />
  8. <result property="ordernum" column="ordernum" />
  9. <collection property="products"
  10. ofType="net.biancheng.po.Product">
  11. <id property="pid" column="pid" />
  12. <result property="name" column="name" />
  13. <result property="price" column="price" />
  14. </collection>
  15. </resultMap>
  16. <select id="selectAllOrdersAndProducts" parameterType="Integer"
  17. resultMap="orderMap">
  18. SELECT o.oid,o.`ordernum`,p.`pid`,p.`name`,p.`price` FROM
  19. `order` o
  20. INNER JOIN orders_detail od ON o.oid=od.`orderId`
  21. INNER JOIN
  22. product p
  23. ON p.pid = od.`productId`
  24. </select>
  25. </mapper>

4. 创建测试类

测试类代码如下。

  1. package net.biancheng.test;
  2. import java.io.IOException;
  3. import java.io.InputStream;
  4. import java.util.List;
  5. import org.apache.ibatis.io.Resources;
  6. import org.apache.ibatis.session.SqlSession;
  7. import org.apache.ibatis.session.SqlSessionFactory;
  8. import org.apache.ibatis.session.SqlSessionFactoryBuilder;
  9. import net.biancheng.mapper.OrderMapper;
  10. import net.biancheng.po.Order;
  11. public class Test {
  12. public static void main(String[] args) throws IOException {
  13. InputStream config = Resources.getResourceAsStream("mybatis-config.xml");
  14. SqlSessionFactory ssf = new SqlSessionFactoryBuilder().build(config);
  15. SqlSession ss = ssf.openSession();
  16. List<Order> orderList = ss.getMapper(OrderMapper.class).selectAllOrdersAndProducts();
  17. for (Order or : orderList) {
  18. System.out.println(or);
  19. }
  20. }
  21. }

运行结果如下。

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]]]

腾讯云推出云产品限时特惠抢购活动:2C2G云服务器7.9元/月起
本文链接:https://www.jhelp.net/p/P0TGJP8dhOcViOPc (转载请保留)。
关注下面的标签,发现更多相似文章