Mybatis之关联
一、一对多关联
eg:一个用户对应多个订单
建表语句
CREATE TABLE `t_customer` (`customer_id` INT NOT NULL AUTO_INCREMENT, `customer_name` CHAR(100), PRIMARY KEY (`customer_id`)
);
CREATE TABLE `t_order` ( `order_id` INT NOT NULL AUTO_INCREMENT, `order_name` CHAR(100), `customer_id` INT, PRIMARY KEY (`order_id`)
);
INSERT INTO `t_customer` (`customer_name`) VALUES ('张三');
INSERT INTO `t_order` (`order_name`, `customer_id`) VALUES ('o1', '1');
INSERT INTO `t_order` (`order_name`, `customer_id`) VALUES ('o2', '1');
INSERT INTO `t_order` (`order_name`, `customer_id`) VALUES ('o3', '1');
关联查询:查询custmoer_id=1的用户的所有订单信息和用户信息
select t_customer.customer_id,customer_name,order_id,order_name from t_customer left JOIN t_order on t_customer.customer_id=t_order.customer_id
where t_customer.customer_id=1
Customer实体类:
@Data
public class Customer {private Integer customerId;private String customerName;
//一个顾客的所有订单private List<Order> orderList;
}
Order实体类:
@Data
public class Order {private Integer orderId;private String orderName;private Integer customerId;}
mapper接口:
Customer getCustomerWithOrders(Integer customerId);
xml配置文件:
<resultMap id="CustomerMap" type="Customer"><id property="customerId" column="customer_id"></id><result property="customerName" column="customer_name"></result><collection property="orderList" ofType="Order"><id property="orderId" column="order_id"></id><result property="orderName" column="order_name"></result></collection></resultMap><select id="getCustomerWithOrders" resultMap="CustomerMap">select t_customer.customer_id,customer_name,order_id,order_name from t_customer left JOIN t_order on t_customer.customer_id=t_order.customer_idwhere t_customer.customer_id=#{customerId}</select>
测试:
@Testpublic void test01(){Customer customerWithOrders = orderMapper.getCustomerWithOrders(1);System.out.println(customerWithOrders);}
在“对多”关联关系中,同样有很多配置,但是提炼出来最关键的就是:“collection”和“ofType”
二、对一关联
eg:一个订单对应一个用户
sql语句:查询订单号为1的订单和用户信息
select t_order.* ,t_customer.customer_name from t_order LEFT JOIN t_customer on t_order.customer_id=t_customer.customer_id
where order_id=1;
查询结果:
order实体类新增Customer属性
@Data
public class Order {private Integer orderId;private String orderName;private Integer customerId;//对一关系,用户信息private Customer customer;
}
mapper接口:
Order getOrderWithCustomer(Integer orderId);
xml配置文件:
<resultMap id="OrderMap" type="Order"><id property="orderId" column="order_id"></id><result property="orderName" column="order_name"></result><association property="customer" javaType="Customer"><id property="customerId" column="customer_id"></id><result property="customerName" column="customer_name"></result></association></resultMap><select id="getOrderWithCustomer" resultMap="OrderMap">select t_order.* ,t_customer.customer_name from t_order LEFT JOIN t_customer on t_order.customer_id=t_customer.customer_idwhere order_id=#{orderId};</select>
测试:
@Testpublic void test02(){Order orderWithCustomer = orderMapper.getOrderWithCustomer(1);System.out.println(orderWithCustomer);}
三、OGNL风格的对一关联
<!-- OGNL风格的对一关联--><select id="getOrderWithCustomer2" resultType="Order">select t_order.order_id,t_order.order_name,t_order.customer_id as 'customer.customerId',t_customer.customer_name as 'customer.customerName' from t_order LEFT JOIN t_customer on t_order.customer_id=t_customer.customer_idwhere order_id=#{orderId};</select>
注意起别名时,对象属性costomer.customerId要加上引号
四、多对多关联
eg:一本书对应多个种类,一个种类对应多本书
建立中间表将书和种类对应起来
①根据书的id,查询对应的具体信息和所属种类的信息:
mapper接口:
/*** 根据书的id,查询对应的具体信息和所属种类的信息* @param bookId* @return*/BookEntity selectBookOfCategories(Integer bookId);
xml配置文件:
<resultMap id="BookMap" type="BookEntity"><id property="id" column="book_id"></id><result property="name" column="name"></result><collection property="categoryEntityList" ofType="CategoryEntity"><id property="categoryId" column="category_id"></id><result property="categoryName" column="category_name"></result></collection></resultMap><select id="selectBookOfCategories" resultMap="BookMap">select book_id,category.category_id,category_name,namefrom books,category,category_bookWHERE books.id=category_book.book_idand category_book.category_id=category.category_idand books.id=#{value}</select>
②根据种类的id,查询所有对应书的信息
mapper接口:
CategoryEntity getCategory(Integer id);
xml配置文件
<resultMap id="CategoryMap" type="CategoryEntity"><id property="categoryId" column="category_id"></id><result property="categoryName" column="category_name"></result><collection property="bookEntityList" ofType="BookEntity"><id property="id" column="book_id"></id><result property="name" column="name"></result></collection></resultMap><select id="getCategory" resultMap="CategoryMap">SELECT name,category.category_id ,category_name,book_idfrom books,category,category_bookWHERE books.id=category_book.book_idand category_book.category_id=category.category_idand category.category_id=#{value};</select>
五、分步查询
①分步查询对多关联
根据id查询顾客=>设置resultMap=>collection中的select指定OrderMapper.xml中的根据顾客id查询所有订单的select语句=>column指定传参(顾客id)
CustomerMapper.xml
<resultMap id="CustomerMap" type="Customer"><id property="customerId" column="customer_id"></id><result property="customerName" column="customer_name"></result><collection property="orderList" select="com.iflytek.mapper.OrderMapper.selectOrderListById" column="customer_id"></collection>
</resultMap><select id="getOrderListByCustomerId" resultMap="CustomerMap">select * from t_customer where customer_id=#{id}
</select>
OrderMapper.xml
<select id="selectOrderListById" resultMap="OrderMap0">select * from t_order where customer_id=#{value}
</select>
<resultMap id="OrderMap0" type="Order"><id property="orderId" column="order_id"></id><result property="orderName" column="order_name"></result>
</resultMap>
关系总览:
②分步查询对一关联
OrderMapper.xml
根据订单id查询订单具体信息=>association标签中的select指定CustomerMapper.xml中的根据customer_id查询顾客信息的slecect语句=>column指定传参customer_id
<resultMap id="OrderMap2" type="Order"><id property="orderId" column="order_id"></id><result property="orderName" column="order_name"></result><association property="customer" select="com.iflytek.mapper.CustomerMapper.getCustomerById" column="customer_id"></association></resultMap><select id="getOrderAndCustomer" resultMap="OrderMap2">select * from t_order where order_id=#{orderId}</select>
CustomerMapper.xml
根据用户id查询用户具体信息
<resultMap id="CustomerMap0" type="Customer"><id property="customerId" column="customer_id"></id><result property="customerName" column="customer_name"></result></resultMap><select id="getCustomerById" resultMap="CustomerMap0">select * from t_customer where customer_id=#{value}
</select>
关系总览:
六、延迟加载
查询到Customer的时候,不一定会使用Order的List集合数据。如果Order的集合数据始终没有使用,那么这部分数据占用的内存就浪费了。对此,我们希望不一定会被用到的数据,能够在需要使用的时候再去查询。
延迟加载的概念:对于实体类关联的属性到需要使用时才查询。也叫懒加载。
yml配置文件中开启懒加载
mybatis:configuration:#开启懒加载lazy-loading-enabled: true
测试:
@Test
public void testSelectCustomerWithOrderList() throws InterruptedException {//对多关联Customer customer = mapper.selectCustomerWithOrderList(1);// 这里必须只打印“customerId或customerName”这样已经加载的属性才能看到延迟加载的效果// 这里如果打印Customer对象整体则看不到效果System.out.println("customer = " + customer.getCustomerName());// 先指定具体的时间单位,然后再让线程睡一会儿TimeUnit.SECONDS.sleep(5);List<Order> orderList = customer.getOrderList();for (Order order : orderList) {System.out.println("order = " + order);}
}
效果:刚开始先查询Customer本身,需要用到OrderList的时候才发送SQL语句去查询
DEBUG 11-30 11:25:31,127 ==> Preparing: select customer_id,customer_name from t_customer where customer_id=? (BaseJdbcLogger.java:145)
DEBUG 11-30 11:25:31,193 ==> Parameters: 1(Integer) (BaseJdbcLogger.java:145)
DEBUG 11-30 11:25:31,314 <== Total: 1 (BaseJdbcLogger.java:145)
customer = c01
DEBUG 11-30 11:25:36,316 ==> Preparing: select order_id,order_name from t_order where customer_id=? (BaseJdbcLogger.java:145)
DEBUG 11-30 11:25:36,316 ==> Parameters: 1(Integer) (BaseJdbcLogger.java:145)
DEBUG 11-30 11:25:36,321 <== Total: 3 (BaseJdbcLogger.java:145)
order = Order{orderId=1, orderName='o1'}
order = Order{orderId=2, orderName='o2'}
order = Order{orderId=3, orderName='o3'}
相关文章:

Mybatis之关联
一、一对多关联 eg:一个用户对应多个订单 建表语句 CREATE TABLE t_customer (customer_id INT NOT NULL AUTO_INCREMENT, customer_name CHAR(100), PRIMARY KEY (customer_id) ); CREATE TABLE t_order ( order_id INT NOT NULL AUTO_INCREMENT, order_name C…...

Labview实现用户界面切换的几种方式---通过VI间相互调用
在做用户界面时我们的程序往往面对的对象是程序使用者,复杂程序如果放在同一个页面中,往往会导致程序冗长卡顿,此时通过多个VI之间的切换就可以实现多个界面之间的转换,也会显得程序更加的高大上。 本文所有程序均可下载ÿ…...
点云从入门到精通技术详解100篇-基于点云和图像融合的智能驾驶目标检测(中)
目录 2.1.2 数据源选型分析 2.2 环境感知系统分析 2.2.1 传感器布置方案分析...
Apache-iotdb物联网数据库的安装及使用
一、简介 >Apache IoTDB (Database for Internet of Things) is an IoT native database with high performance for data management and analysis, deployable on the edge and the cloud. Due to its light-weight architecture, high performance and rich feature set…...

项目管理流程
优质博文 IT-BLOG-CN 一、简介 项目是为提供某项独特产品【独特指:创造出与以往不同或者多个方面与以往有所区别产品或服务,所以日复一日重复的工作就不属于项目】、服务或成果所做的临时性【临时性指:项目有明确的开始时间和明确的结束时间,不会无限期…...

0004.电脑开机提示按F1
常用的电脑主板不知道什么原因,莫名其妙的启动不了了。尝试了很多方法,没有奏效。没有办法我就只能把硬盘拆了下来,装到了另一台电脑上面。但是开机以后却提示F1,如下图: 根据上面的提示,应该是驱动有问题…...

中国电子学会2022年12月份青少年软件编程Scratch图形化等级考试试卷一级真题(含答案)
一、单选题(共25题,共50分) 1. 小明想在开始表演之前向大家问好并做自我介绍,应运行下列哪个程序?(2分) A. B. C. D. 2. 舞台有两个不同的背景,小猫角色的哪个积木能够切换舞台背景?(2分) A. B. C. D. 3. …...

C语言第二弹---C语言基本概念(下)
✨个人主页: 熬夜学编程的小林 💗系列专栏: 【C语言详解】 【数据结构详解】 C语言基本概念 1、字符串和\02、转义字符3、语句和语句分类3.1、空语句3.2、表达式语句3.3、函数调⽤语句3.4、复合语句3.5、控制语句 4、注释4.1、注释的两种形…...

Java 基础面试题 String(一)
Java 基础面试题 String(一) 文章目录 Java 基础面试题 String(一)String、StringBuffer、StringBuilder 的区别?String 为什么是不可变的?字符串拼接用“” 还是 StringBuilder? 文章来自Java Guide 用于学习如有侵…...
QT中QApplication对象有且只有一个
QT中QApplication对象有且只有一个 QApplication对象 QApplication对象 QApplication是应用程序对象 #include <QApplication> int main(int argc,char* argv[]); {//a对象在一个程序中有且只有一个,QT中要求必须有一个QApplication a(argc,argv…...

HTML CSS 发光字头特效
效果展示: 代码: <html><head> </head><style>*{margin: 0;padding: 0;}body {text-align: center;}h1{/* border: 3px solid rgb(201, 201, 201); */margin-bottom: 20px;}.hcqFont {position: relative;letter-spacing: 0.07…...

4.postman批量运行及json、cvs文件运行
一、批量运行collection 1.各个接口设置信息已保存,在collection中点击run collection 2.编辑并运行集合 集合运行时,单独上传图片时报错。需修改postman设置 二、csv文件运行 可新建记事本,输入测试数据,后另存为新的文本文件&…...
Superset二次开发之集成链路追踪TraceID技术
config.py ##时间-日志级别-完整路径-文件名字-文件行-函数名字-信息 LOG_FORMAT = "%(asctime)s:%(levelname)s:%(pathname)s:%(module)s:%(lineno)d:%(funcName)s:%(message)s" 字符串详细信息 格式字符串作用%(name)s日志记录器的名称(记录通道)%(levelno)s日…...

商品详情APP端原数据淘宝数据采集API接口代码接入示例
商品详情APP端原数据API接口(接口接入入口)的作用是提供APP端商品的详细信息,包括价格、描述、图片、折后价、优惠券信息等。通过调用这个API接口,开发者可以获取到APP端商品详情相关的数据,从而进行数据分析ÿ…...
企业官网搭建:打造专业形象的关键步骤
企业官网是企业在数字世界中的门面,搭建一个专业、功能齐全的官网对于企业的形象和业务发展至关重要。以下是一些关键的步骤: 一、确定目标和需求 明确网站的目标、受众和主要功能,为设计和内容提供指导。 二、域名和主机选择 选择易于记忆和…...

Vue2移动端项目使用$router.go(-1)不生效问题记录
目录 1、this.$router.go(-1) 改成 this.$router.back() 2、存储 from.path,使用 this.$router.push 3、hash模式中使用h5新增的onhashchange事件做hack处理 4、this.$router.go(-1) 之前添加一个 replace 方法 问题背景 : 在 Vue2 的一个移动端开发…...

ChatGPT与文心一言:AI助手之巅的对决
随着科技的飞速发展,人工智能助手已经渗透到我们的日常生活和工作中。 而在这个充满竞争的领域里,ChatGPT和文心一言无疑是最引人注目的两款产品。它们各自拥有独特的优势,但在智能回复、语言准确性、知识库丰富度等方面却存在差异。那么&am…...

前端实现贪吃蛇功能
大家都玩过贪吃蛇小游戏,控制一条蛇去吃食物,然后蛇在吃到食物后会变大。本篇博客将会实现贪吃蛇小游戏的功能。 1.实现效果 2.整体布局 /*** 游戏区域样式*/ const gameBoardStyle {gridTemplateColumns: repeat(${width}, 1fr),gridTemplateRows: re…...

文件操作(上)
目录 文件的必要性: 文件分类: 程序文件: 数据文件: 文件的打开与关闭: fopen函数分析: 编辑 FILE*: char*filename: char*mode: fclose函数: 应用: 文件编译 Fgetc Fputc 应用…...

用CHAT写年终总结
问CHAT:写一份政企经理年度总结 CHAT回复:尊敬的同事和领导: 大家好,我是负责政企业务的经理,全年一直坚守在销售一线,为公司带来更多的企业客户并拓展业务领域。感谢领导和同事在工作中的大力支持与热情协…...

vscode(仍待补充)
写于2025 6.9 主包将加入vscode这个更权威的圈子 vscode的基本使用 侧边栏 vscode还能连接ssh? debug时使用的launch文件 1.task.json {"tasks": [{"type": "cppbuild","label": "C/C: gcc.exe 生成活动文件"…...
FastAPI 教程:从入门到实践
FastAPI 是一个现代、快速(高性能)的 Web 框架,用于构建 API,支持 Python 3.6。它基于标准 Python 类型提示,易于学习且功能强大。以下是一个完整的 FastAPI 入门教程,涵盖从环境搭建到创建并运行一个简单的…...
Python爬虫实战:研究feedparser库相关技术
1. 引言 1.1 研究背景与意义 在当今信息爆炸的时代,互联网上存在着海量的信息资源。RSS(Really Simple Syndication)作为一种标准化的信息聚合技术,被广泛用于网站内容的发布和订阅。通过 RSS,用户可以方便地获取网站更新的内容,而无需频繁访问各个网站。 然而,互联网…...
Leetcode 3577. Count the Number of Computer Unlocking Permutations
Leetcode 3577. Count the Number of Computer Unlocking Permutations 1. 解题思路2. 代码实现 题目链接:3577. Count the Number of Computer Unlocking Permutations 1. 解题思路 这一题其实就是一个脑筋急转弯,要想要能够将所有的电脑解锁&#x…...
postgresql|数据库|只读用户的创建和删除(备忘)
CREATE USER read_only WITH PASSWORD 密码 -- 连接到xxx数据库 \c xxx -- 授予对xxx数据库的只读权限 GRANT CONNECT ON DATABASE xxx TO read_only; GRANT USAGE ON SCHEMA public TO read_only; GRANT SELECT ON ALL TABLES IN SCHEMA public TO read_only; GRANT EXECUTE O…...
Spring Boot+Neo4j知识图谱实战:3步搭建智能关系网络!
一、引言 在数据驱动的背景下,知识图谱凭借其高效的信息组织能力,正逐步成为各行业应用的关键技术。本文聚焦 Spring Boot与Neo4j图数据库的技术结合,探讨知识图谱开发的实现细节,帮助读者掌握该技术栈在实际项目中的落地方法。 …...

前端开发面试题总结-JavaScript篇(一)
文章目录 JavaScript高频问答一、作用域与闭包1.什么是闭包(Closure)?闭包有什么应用场景和潜在问题?2.解释 JavaScript 的作用域链(Scope Chain) 二、原型与继承3.原型链是什么?如何实现继承&a…...

SpringCloudGateway 自定义局部过滤器
场景: 将所有请求转化为同一路径请求(方便穿网配置)在请求头内标识原来路径,然后在将请求分发给不同服务 AllToOneGatewayFilterFactory import lombok.Getter; import lombok.Setter; import lombok.extern.slf4j.Slf4j; impor…...

ArcGIS Pro制作水平横向图例+多级标注
今天介绍下载ArcGIS Pro中如何设置水平横向图例。 之前我们介绍了ArcGIS的横向图例制作:ArcGIS横向、多列图例、顺序重排、符号居中、批量更改图例符号等等(ArcGIS出图图例8大技巧),那这次我们看看ArcGIS Pro如何更加快捷的操作。…...
【Go语言基础【13】】函数、闭包、方法
文章目录 零、概述一、函数基础1、函数基础概念2、参数传递机制3、返回值特性3.1. 多返回值3.2. 命名返回值3.3. 错误处理 二、函数类型与高阶函数1. 函数类型定义2. 高阶函数(函数作为参数、返回值) 三、匿名函数与闭包1. 匿名函数(Lambda函…...