本文目标:以主表(orders订单表)和 另外两个关联表(orderdetail 订单详细表,user 用户表)进行一对多查询。
1、新建数据表(四张表)和添加测试数据
为了测试,我这里随便填了些数据
2、思路分析
订单项和订单明细是一对多的关系,所以本文主要来查询订单表,然后关联订单明细表,这样就有一对多的问题出来了。
首先还是先写sql语句,在写sql语句的时候遵循两点:
明确了主表和关联表,下面就可以写sql了,我们在上一节的sql基础上添加订单明细表的关联即可。
这样我们就查询出了订单表中的所有字段,user表和orderdetail表的部分字段,当然也可以查询所有字段,这个根据具体需求来定。看一下查询结果:
1、新建三个持久类
① User.java
② Orderdetail.java
③ Orders.java
注意:我们的orders 表作为主表,orders类当然需要扩展其他关联表的属性
2、OrdersMapperCustom.java
3、OrdersMapperCustom.xml 映射文件
注意:
4、测试类 OrdersMapperCustomTest.java
还有其他文件就不补充了,如 mybatis 全局配置文件
参考:传智播客视频
本文链接:https://liuyanzhao.com/5847.html
一、开发准备
1、新建数据表(四张表)和添加测试数据
- DROP TABLE IF EXISTS `items`;
- DROP TABLE IF EXISTS `orders`;
- DROP TABLE IF EXISTS `user`;
- DROP TABLE IF EXISTS `orderdetail`;
- /*items是商品表*/
- CREATE TABLE `items` (
- `id` INT(11) NOT NULL AUTO_INCREMENT,
- `name` VARCHAR(32) NOT NULL COMMENT '商品名称',
- `price` FLOAT(10,1) NOT NULL COMMENT '商品定价',
- `detail` TEXT COMMENT '商品描述',
- `pic` VARCHAR(64) DEFAULT NULL COMMENT '商品图片',
- `createtime` DATETIME NOT NULL COMMENT '生产日期',
- PRIMARY KEY (`id`)
- ) ENGINE=INNODB AUTO_INCREMENT=4 DEFAULT CHARSET=utf8;
- /*user是用户表*/
- CREATE TABLE `user` (
- `id` INT(11) NOT NULL AUTO_INCREMENT,
- `username` VARCHAR(32) NOT NULL COMMENT '用户名称',
- `birthday` DATE DEFAULT NULL COMMENT '生日',
- `gender` CHAR(1) DEFAULT NULL COMMENT '性别',
- `address` VARCHAR(256) DEFAULT NULL COMMENT '地址',
- PRIMARY KEY (`id`)
- ) ENGINE=INNODB AUTO_INCREMENT=27 DEFAULT CHARSET=utf8;
- /*orders是订单表*/
- CREATE TABLE `orders` (
- `id` INT(11) NOT NULL AUTO_INCREMENT,
- `user_id` INT(11) NOT NULL COMMENT '下单用户id',
- `number` VARCHAR(32) NOT NULL COMMENT '订单号',
- `createtime` DATETIME NOT NULL COMMENT '创建订单时间',
- `note` VARCHAR(100) DEFAULT NULL COMMENT '备注',
- PRIMARY KEY (`id`),
- KEY `FK_orders_1` (`user_id`),
- CONSTRAINT `FK_orders_id` FOREIGN KEY (`user_id`) REFERENCES `user` (`id`) ON DELETE NO ACTION ON UPDATE NO ACTION
- ) ENGINE=INNODB AUTO_INCREMENT=6 DEFAULT CHARSET=utf8;
- /*orderdetail是订单明细表*/
- DROP TABLE IF EXISTS orderdetail;
- CREATE TABLE `orderdetail` (
- `id` INT(11) NOT NULL AUTO_INCREMENT,
- `orders_id` INT(11) NOT NULL COMMENT '订单id',
- `items_id` INT(11) NOT NULL COMMENT '商品id',
- `items_num` INT(11) DEFAULT NULL COMMENT '商品购买数量',
- PRIMARY KEY (`id`),
- KEY `FK_orderdetail_1` (`orders_id`),
- KEY `FK_orderdetail_2` (`items_id`),
- CONSTRAINT `FK_orderdetail_1` FOREIGN KEY (`orders_id`) REFERENCES `orders` (`id`) ON DELETE NO ACTION ON UPDATE NO ACTION,
- CONSTRAINT `FK_orderdetail_2` FOREIGN KEY (`items_id`) REFERENCES `items` (`id`) ON DELETE NO ACTION ON UPDATE NO ACTION
- ) ENGINE=INNODB AUTO_INCREMENT=5 DEFAULT CHARSET=utf8;
为了测试,我这里随便填了些数据
2、思路分析
订单项和订单明细是一对多的关系,所以本文主要来查询订单表,然后关联订单明细表,这样就有一对多的问题出来了。
首先还是先写sql语句,在写sql语句的时候遵循两点:
- 查询的主表是哪个? 订单表
- 查询的关联表是哪个? 订单明细表
明确了主表和关联表,下面就可以写sql了,我们在上一节的sql基础上添加订单明细表的关联即可。
- <!--查询订单关联查询用户及订单明细-->
- <select id="findOrdersAndOrderDetailResultMap" resultMap="OrdersAndOrderDetailResultMap">
- SELECT
- orders.*,
- user.username,
- user.gender,
- user.address,
- orderdetail.id orderdetail_id,
- orderdetail.items_id,
- orderdetail.items_num,
- orderdetail.orders_id
- FROM
- orders,
- user,
- orderdetail
- WHERE orders.user_id=user.id AND orders.id = orderdetail.orders_id
- </select>
这样我们就查询出了订单表中的所有字段,user表和orderdetail表的部分字段,当然也可以查询所有字段,这个根据具体需求来定。看一下查询结果:
二、代码实现
1、新建三个持久类
① User.java
- package com.liuyanzhao.mybatis.po;
- import java.util.Date;
- /**
- * 用户的持久类
- */
- public class User {
- private int id; //编号
- private String username; //用户名
- private String gender; //性别
- private Date birthday; //生日
- private String address; //地址
- public int getId() {
- return id;
- }
- public void setId(int id) {
- this.id = id;
- }
- public String getUsername() {
- return username;
- }
- public void setUsername(String username) {
- this.username = username;
- }
- public String getGender() {
- return gender;
- }
- public void setGender(String gender) {
- this.gender = gender;
- }
- public Date getBirthday() {
- return birthday;
- }
- public void setBirthday(Date birthday) {
- this.birthday = birthday;
- }
- public String getAddress() {
- return address;
- }
- public void setAddress(String address) {
- this.address = address;
- }
- }
② Orderdetail.java
- package com.liuyanzhao.mybatis.po;
- /**
- * 订单明细的持久类
- */
- public class Orderdetail {
- private int id;
- private int ordersId;
- private int itemsId;
- private int itemsNum;
- public int getId() {
- return id;
- }
- public void setId(int id) {
- this.id = id;
- }
- public int getOrdersId() {
- return ordersId;
- }
- public void setOrdersId(int ordersId) {
- this.ordersId = ordersId;
- }
- public int getItemsId() {
- return itemsId;
- }
- public void setItemsId(int itemsId) {
- this.itemsId = itemsId;
- }
- public int getItemsNum() {
- return itemsNum;
- }
- public void setItemsNum(int itemsNum) {
- this.itemsNum = itemsNum;
- }
- }
③ Orders.java
- package com.liuyanzhao.mybatis.po;
- import java.util.Date;
- import java.util.List;
- /**
- * 订单的持久类和扩展类
- */
- public class Orders {
- private int id;
- private int userId;
- private String number;
- private Date createTime;
- private String note;
- //用户信息
- private User user;
- //订单明细
- private List<Orderdetail> orderdetails;
- public User getUser() {
- return user;
- }
- public void setUser(User user) {
- this.user = user;
- }
- public List<Orderdetail> getOrderdetails() {
- return orderdetails;
- }
- public void setOrderdetails(List<Orderdetail> orderdetails) {
- this.orderdetails = orderdetails;
- }
- public int getId() {
- return id;
- }
- public void setId(int id) {
- this.id = id;
- }
- public int getUserId() {
- return userId;
- }
- public void setUserId(int userId) {
- this.userId = userId;
- }
- public String getNumber() {
- return number;
- }
- public void setNumber(String number) {
- this.number = number;
- }
- public Date getCreateTime() {
- return createTime;
- }
- public void setCreateTime(Date createTime) {
- this.createTime = createTime;
- }
- public String getNote() {
- return note;
- }
- public void setNote(String note) {
- this.note = note;
- }
- }
注意:我们的orders 表作为主表,orders类当然需要扩展其他关联表的属性
2、OrdersMapperCustom.java
- package com.liuyanzhao.mybatis.mapper;
- import com.liuyanzhao.mybatis.po.Orders;
- import java.util.List;
- /**
- * 订单 mapper
- */
- public interface OrdersMapperCustom {
- //查询订单(关联用户)及订单明细
- public List<Orders> findOrdersAndOrderDetailResultMap() throws Exception;
- }
3、OrdersMapperCustom.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.liuyanzhao.mybatis.mapper.OrdersMapperCustom">
- <!--订单和订单明细的resultMap-->
- <resultMap id="OrdersAndOrderDetailResultMap" type="com.liuyanzhao.mybatis.po.Orders">
- <!--订单信息-->
- <!--
- id:指定查询到的唯一标识符
- column:订单信息的唯一表示列
- property:订单信息的唯一标识列所映射到Orders中哪个属性
- -->
- <id column="id" property="id"></id>
- <result column="user_id" property="userId"></result>
- <result column="number" property="number"></result>
- <result column="createtime" property="createTime"></result>
- <result column="note" property="note"></result>
- <!--用户信息-->
- <!--
- association;用于映射关联查询单个对象的信息
- property:要将关联查询的用户信息映射到orders中的哪个属性
- -->
- <association property="user" javaType="com.liuyanzhao.mybatis.po.User">
- <id column="user_id" property="id"></id>
- <result column="username" property="username"></result>
- <result column="gender" property="gender"></result>
- <result column="address" property="address"></result>
- </association>
- <!--订单明细信息-->
- <!--
- 一个订单中关联查询多条明细,要是用collection进行映射
- collection:对关联查询到多条记录映射到集合对象中
- property:将关联查询到的多条记录映射到Orders哪个属性
- ofType:指定映射到集合属性中pojo的类型
- -->
- <collection property="orderdetails" ofType="com.liuyanzhao.mybatis.po.Orderdetail">
- <id column="orderdetail_id" property="id"></id>
- <result column="items_id" property="itemsId"></result>
- <result column="items_num" property="itemsNum"></result>
- <result column="orders_id" property="ordersId"></result>
- </collection>
- </resultMap>
- <!--查询订单关联查询用户及订单明细-->
- <select id="findOrdersAndOrderDetailResultMap" resultMap="OrdersAndOrderDetailResultMap">
- SELECT
- orders.*,
- user.username,
- user.gender,
- user.address,
- orderdetail.id orderdetail_id,
- orderdetail.items_id,
- orderdetail.items_num,
- orderdetail.orders_id
- FROM
- orders,
- user,
- orderdetail
- WHERE orders.user_id=user.id AND orders.id = orderdetail.orders_id
- </select>
- </mapper>
注意:
- <resultMap>的 id 是一个唯一标识符;type 相当于 resultType,表示查询的返回值类型。
- <select>标签的 resultMap 要和 <resultMap>标签的 id 一致
- association 和collection 两个标签的区别:
4、测试类 OrdersMapperCustomTest.java
- package com.liuyanzhao.mybatis.test;
- import com.liuyanzhao.mybatis.mapper.OrdersMapperCustom;
- import com.liuyanzhao.mybatis.po.Orders;
- 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 org.junit.Before;
- import org.junit.Test;
- import java.io.InputStream;
- import java.util.List;
- /**
- * Created by Liu_Yanzhao on 2017/8/12.
- */
- public class OrdersMapperCustomTest {
- SqlSessionFactory sqlSessionFactory;
- @Before
- public void setUp() throws Exception {
- String resource = "Configuration.xml";
- InputStream inputStream = Resources.getResourceAsStream(resource);
- sqlSessionFactory = new SqlSessionFactoryBuilder()
- .build(inputStream);
- }
- @Test
- public void testFindOrdersAndOrderDetailResultMap() throws Exception {
- SqlSession sqlSession = sqlSessionFactory.openSession();
- //创建代理对象
- OrdersMapperCustom ordersMapperCustom = sqlSession.getMapper(OrdersMapperCustom.class);
- //调用mapper对象
- List<Orders> list = ordersMapperCustom.findOrdersAndOrderDetailResultMap();
- System.out.println(list);
- //释放资源
- sqlSession.close();
- }
- }
还有其他文件就不补充了,如 mybatis 全局配置文件
参考:传智播客视频
本文链接:https://liuyanzhao.com/5847.html
您可以选择一种方式赞助本站
支付宝扫一扫赞助
微信钱包扫描赞助
赏