MyBatis 如何实现一个多对多的关联查询呢?
下文将通过示例的方式,讲述多对多的关联查询,如下所示:
例 ,一个订单可以有多种商品,
一种商品可以对应多个订单,
订单与商品就是多对多的级联关系
可以使用一个中间表(订单记录表)将多对多级联转换成两个一对多的关系
例 下面以订单和商品(实现“查询所有订单以及每个订单对应的商品信息”的功能)为例讲解多对多关联查询
DEBUG [main] - ==Parameters:
例 ,一个订单可以有多种商品,
一种商品可以对应多个订单,
订单与商品就是多对多的级联关系
可以使用一个中间表(订单记录表)将多对多级联转换成两个一对多的关系
例 下面以订单和商品(实现“查询所有订单以及每个订单对应的商品信息”的功能)为例讲解多对多关联查询
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 com.java265.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 com.java265.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 com.java265.mapper; import java.util.List; import com.java265.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="com.java265.mapper.OrderMapper"> <resultMap type="com.java265.po.Order" id="orderMap"> <id property="oid" column="oid" /> <result property="ordernum" column="ordernum" /> <collection property="products" ofType="com.java265.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 com.java265.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 com.java265.mapper.OrderMapper; import com.java265.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]]]
版权声明
本文仅代表作者观点,不代表本站立场。
本文系作者授权发表,未经许可,不得转载。