MyBatis中一对多关系的两种处理方法

目录

1.多表联查(通过collection标签的ofType属性)

1)mapper

2)mapper.xml

3)测试代码

4)测试结果

2.分布查询(通过collection标签的select属性)

1)mapper

2)mapper.xml

3)测试代码

4)测试结果

附录

1.Classes实体类

2.student类

3.OneToManyMapper

4.OneToManyMapper.xml

5.OneToManyMapperTest.xml

 6.sql

studentSql

classesSql


1.多表联查(通过collection标签的ofType属性)

1)mapper

/*** collectionBy ofType*/
Classes queryClassesAndStudentBycollection(@Param("id") int id);

2)mapper.xml

<!--collection-->
<resultMap id="collectionResultMap" type="org.xiji.enty.Classes"><id property="cid" column="cid"/><result property="className" column="className"/><!--collection--><collection property="students" ofType="org.xiji.enty.Student"><id property="sid" column="sid"/><result property="studentName" column="studentName"/><result property="studentAge" column="studentAge"/><result property="classId" column="cid"/></collection></resultMap>
<select id="queryClassesAndStudentBycollection" resultMap="collectionResultMap" >select * from classes c right join student s on c.cid = s.classId where c.cid=#{id}
</select>

解释:

  1. 主对象映射
    1. MyBatis 使用 resultMap 将查询结果映射到 Classes 对象上。
    2. 主键 cid 和属性 className 直接映射到对应的数据库列。
  2. 集合映射
    1. collection 标签用于映射 Classes 对象中的 students 集合。
    2. 每个 Student 对象的属性 sid, studentName, studentAge, classId 分别映射到对应的数据库列。

3)测试代码

/*** 通过collection关联查询*/
@Test
public void queryClassesAndStudentByAssociation()
{Classes classes = oneToManyMapper.queryClassesAndStudentBycollection(1);System.out.println(classes);List<Student> students = classes.getStudents();for (Student student : students) {System.out.println(student.toString());}
}

4)测试结果

2.分布查询(通过collection标签的select属性)

1)mapper

/*** 分布查询*/
Classes queryClassesAndStudentByStep(@Param("id") int id);/*** 查询id*/
List<Student> queryClassesAndStudentByStepTwo(int id);

2)mapper.xml

<!--通过分布查询-->
<resultMap id="stepResultMap" type="org.xiji.enty.Classes"><id property="cid" column="cid"/><result property="className" column="className"/><collection property="students"select="queryClassesAndStudentByStepTwo"column="cid"ofType="org.xiji.enty.Student"><id property="sid" column="sid"></id><result property="classId" column="classId"></result><result property="studentName" column="studentName"></result><result property="studentAge" column="studentAge"></result></collection></resultMap><select id="queryClassesAndStudentByStep" resultMap="stepResultMap" >select *from classes where cid=#{id};
</select><select id="queryClassesAndStudentByStepTwo" resultType="org.xiji.enty.Student">select * from student where classId=#{id}
</select>j

解释:

  1. 主对象映射
    1. MyBatis 使用 resultMap 将查询结果映射到 Classes 对象上。
    2. 主键 cid 和属性 className 直接映射到对应的数据库列。
  2. 分布查询
    1. collection 标签用于映射 Classes 对象中的 students 集合。
    2. 通过 select 属性指定另一个映射语句的 ID,用于执行分布查询。
    3. column 属性指定传递给分布查询的参数列名称,这里是 cid 列。
  3. 子对象映射
    1. 每个 Student 对象的属性 sid, classId, studentName, studentAge 分别映射到对应的数据库列。


 

3)测试代码

/*** 通过collection分布查询*/
@Test
public void queryClassesAndStudentByStep()
{Classes classes = oneToManyMapper.queryClassesAndStudentByStep(1);System.out.println(classes);List<Student> students = classes.getStudents();for (Student student : students) {System.out.println(student);}
}

4)测试结果

附录

1.Classes实体类

package org.xiji.enty;import java.util.ArrayList;
import java.util.List;
import org.xiji. enty.Student;/*** 班级表*/
public class Classes {private int cid;private String className;List<Student> students;public List<Student> getStudents() {return students;}public Classes(int id, String className, List<Student> students) {this.cid = id;this.className = className;this.students = students;}public Classes() {students = new ArrayList<>();}public Classes(int id, String className) {this.cid = id;this.className = className;}public int getId() {return cid;}public void setId(int id) {this.cid = id;}public String getClassName() {return className;}public void setClassName(String className) {this.className = className;}public void setStudents(List<Student> students) {this.students = students;}@Overridepublic String toString() {return "Classes{" +"id=" + cid +", className='" + className + '\'' +", students=" + students +'}';}
}

2.student类

package org.xiji.enty;
import org.xiji.enty.Classes;/*** 学生表*/
public class Student {private int sid;private String studentName;private int studentAge;private int classId;private Classes classes;public Student(int id, String studentName, int studentAge, int classId, Classes classes) {this.sid = id;this.studentName = studentName;this.studentAge = studentAge;this.classId = classId;this.classes = classes;}public Student(int id, String studentName, int studentAge, int classId) {this.sid = id;this.studentName = studentName;this.studentAge = studentAge;this.classId = classId;}public Student() {}public int getId() {return sid;}public void setId(int id) {this.sid = id;}public String getStudentName() {return studentName;}public void setStudentName(String studentName) {this.studentName = studentName;}public int getStudentAge() {return studentAge;}public void setStudentAge(int studentAge) {this.studentAge = studentAge;}public int getClassId() {return classId;}public void setClassId(int classId) {this.classId = classId;}public Classes getClasses() {return classes;}public void setClasses(Classes classes) {this.classes = classes;}public void setClasses(int id,String className){this.classes = new Classes(id,className);}@Overridepublic String toString() {return "Student{" +"id=" + sid +", studentName='" + studentName + '\'' +", studentAge=" + studentAge +", classId=" + classId +", classes=" + classes +'}';}
}

3.OneToManyMapper

package org.xiji.mapper;import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
import org.xiji.enty.Classes;
import org.xiji.enty.Student;import java.util.List;@Mapper
public interface OneToManyMapper {/*** association*/Classes queryClassesAndStudentByAssociation(@Param("id") int id);/*** 分布查询*/Classes queryClassesAndStudentByStep(@Param("id") int id);/*** 查询id*/List<Student> queryClassesAndStudentByStepTwo(int id);}

4.OneToManyMapper.xml

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapperPUBLIC "-//mybatis.org//DTD Mapper 3.0//EN""http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="org.xiji.mapper.OneToManyMapper"><!--collection--><resultMap id="collectionResultMap" type="org.xiji.enty.Classes"><id property="cid" column="cid"/><result property="className" column="className"/><!--collection--><collection property="students" ofType="org.xiji.enty.Student"><id property="sid" column="sid"/><result property="studentName" column="studentName"/><result property="studentAge" column="studentAge"/><result property="classId" column="cid"/></collection></resultMap><select id="queryClassesAndStudentByAssociation" resultMap="collectionResultMap" >select * from classes c right join student s on c.cid = s.classId where c.cid=#{id}</select><!--通过分布查询--><resultMap id="stepResultMap" type="org.xiji.enty.Classes"><id property="cid" column="cid"/><result property="className" column="className"/><collection property="students"select="queryClassesAndStudentByStepTwo"column="cid"ofType="org.xiji.enty.Student"><id property="sid" column="sid"></id><result property="classId" column="classId"></result><result property="studentName" column="studentName"></result><result property="studentAge" column="studentAge"></result></collection></resultMap><select id="queryClassesAndStudentByStep" resultMap="stepResultMap" >select *from classes where cid=#{id};</select><select id="queryClassesAndStudentByStepTwo" resultType="org.xiji.enty.Student">select * from student where classId=#{id}</select></mapper>

5.OneToManyMapperTest.xml

import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.junit.jupiter.SpringJUnitConfig;
import org.xiji.enty.Classes;
import org.xiji.enty.Student;
import org.xiji.mapper.ManyToOneMapper;
import org.xiji.mapper.OneToManyMapper;import java.util.List;@SpringJUnitConfig(locations = {"classpath:springConfig.xml"})
public class OneTwoManyMapperTest {@Autowiredprivate OneToManyMapper oneToManyMapper;/*** 通过collection关联查询*/@Testpublic void queryClassesAndStudentByAssociation(){Classes classes = oneToManyMapper.queryClassesAndStudentByAssociation(1);System.out.println(classes);List<Student> students = classes.getStudents();for (Student student : students) {System.out.println(student.toString());}}/*** 通过collection分布查询*/@Testpublic void queryClassesAndStudentByStep(){Classes classes = oneToManyMapper.queryClassesAndStudentByStep(1);System.out.println(classes);List<Student> students = classes.getStudents();for (Student student : students) {System.out.println(student);}}
}

 6.sql

studentSql

/*Navicat Premium Data TransferSource Server         : mybatisSource Server Type    : MySQLSource Server Version : 80025Source Host           : localhost:3306Source Schema         : mybatisTarget Server Type    : MySQLTarget Server Version : 80025File Encoding         : 65001Date: 15/09/2024 23:50:47
*/SET NAMES utf8mb4;
SET FOREIGN_KEY_CHECKS = 0;-- ----------------------------
-- Table structure for student
-- ----------------------------
DROP TABLE IF EXISTS `student`;
CREATE TABLE `student`  (`sid` int NOT NULL AUTO_INCREMENT COMMENT '学生id',`studentName` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NULL DEFAULT NULL COMMENT '学生姓名',`studentAge` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NULL DEFAULT NULL COMMENT '学生年龄',`classId` int NULL DEFAULT NULL COMMENT '班级id',PRIMARY KEY (`sid`) USING BTREE,INDEX `classId`(`classId` ASC) USING BTREE,CONSTRAINT `classId` FOREIGN KEY (`classId`) REFERENCES `classes` (`cid`) ON DELETE RESTRICT ON UPDATE RESTRICT
) ENGINE = InnoDB CHARACTER SET = utf8mb4 COLLATE = utf8mb4_0900_ai_ci ROW_FORMAT = Dynamic;-- ----------------------------
-- Records of student
-- ----------------------------
INSERT INTO `student` VALUES (1, '张三', '18', 1);
INSERT INTO `student` VALUES (2, '李四', '20', 1);
INSERT INTO `student` VALUES (3, '小久', '21', 1);
INSERT INTO `student` VALUES (4, 'xiji', '22', 1);SET FOREIGN_KEY_CHECKS = 1;

classesSql

/*Navicat Premium Data TransferSource Server         : mybatisSource Server Type    : MySQLSource Server Version : 80025Source Host           : localhost:3306Source Schema         : mybatisTarget Server Type    : MySQLTarget Server Version : 80025File Encoding         : 65001Date: 15/09/2024 23:51:16
*/SET NAMES utf8mb4;
SET FOREIGN_KEY_CHECKS = 0;-- ----------------------------
-- Table structure for classes
-- ----------------------------
DROP TABLE IF EXISTS `classes`;
CREATE TABLE `classes`  (`cid` int NOT NULL AUTO_INCREMENT COMMENT '班级id',`className` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NULL DEFAULT NULL COMMENT '班级名称',PRIMARY KEY (`cid`) USING BTREE
) ENGINE = InnoDB CHARACTER SET = utf8mb4 COLLATE = utf8mb4_0900_ai_ci ROW_FORMAT = Dynamic;-- ----------------------------
-- Records of classes
-- ----------------------------
INSERT INTO `classes` VALUES (1, '一班');
INSERT INTO `classes` VALUES (2, '二班');
INSERT INTO `classes` VALUES (3, '三班');
INSERT INTO `classes` VALUES (5, '五班');SET FOREIGN_KEY_CHECKS = 1;

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.xdnf.cn/news/1536139.html

如若内容造成侵权/违法违规/事实不符,请联系一条长河网进行投诉反馈,一经查实,立即删除!

相关文章

优化算法(三)—模拟退火算法(附MATLAB程序)

模拟退火算法&#xff08;Simulated Annealing, SA&#xff09;是一种基于概率的优化算法&#xff0c;旨在寻找全局最优解。该算法模拟金属退火过程中的物质冷却过程&#xff0c;逐渐降低系统的“温度”以达到全局优化的效果。它特别适用于解决复杂的组合优化问题。 一、模拟退…

[产品管理-21]:NPDP新产品开发 - 19 - 产品设计与开发工具 - 详细设计与规格定义

目录 前言&#xff1a; 一、详细设计与规格定义概述 1、产品详细设计 2、规格定义 3、详细设计与规格定义的关系 4、实际应用中的注意事项 二、详细设计与规格定义主要工具 2.1 质量功能展开QFD - 需求跟踪矩阵 1、QFD的基本原理 2、QFD的实施步骤 3、QFD的优势与应…

人工智能开发实战matplotlib库应用基础

内容导读 matplotlib简介绘制直方图绘制撒点图 一、matplotlib简介 matplotlib是一个Python 2D绘图库&#xff0c;它以多种硬拷贝格式和跨平台的交互式环境生成高质量的图形。 matplotlib 尝试使容易的事情变得更容易&#xff0c;使困难的事情变得可能。 我们只需几行代码…

解锁全球机遇:澳大利亚服务器租用市场的独特魅力

在浩瀚的全球数字版图中&#xff0c;澳大利亚以其独特的地理位置、丰富的资源禀赋、以及日益增长的数字经济活力&#xff0c;成为了众多互联网企业竞相布局的重要市场。特别是当谈及服务器租用这一关键环节时&#xff0c;澳大利亚以其稳定的网络环境、先进的基础设施和开放的市…

[数据集][目标检测]智慧交通铁路异物入侵检测数据集VOC+YOLO格式802张7类别

数据集格式&#xff1a;Pascal VOC格式YOLO格式(不包含分割路径的txt文件&#xff0c;仅仅包含jpg图片以及对应的VOC格式xml文件和yolo格式txt文件) 图片数量(jpg文件个数)&#xff1a;802 标注数量(xml文件个数)&#xff1a;802 标注数量(txt文件个数)&#xff1a;802 标注类别…

知识竞赛活动舞台搭建要多少钱

每次举办活动&#xff0c;舞台搭建总是让人头疼的一部分&#xff0c;尤其是费用问题。今天就来揭开活动舞台搭建费用的神秘面纱。 活动舞台搭建的费用主要包括舞台结构、设备、音响、灯光、舞美装饰等各方面的成本。具体来说&#xff1a; 1.舞台结构&#xff1a;包括舞台平台…

5.TensorBoard的使用(二)--add_image()

TensorBoard的使用&#xff08;二&#xff09; 1.使用add_image()给添加图片 首先导入Tensorboard包 from torch.utils.tensorboard import SummaryWriter创建一个SummaryWriter类的实例&#xff0c;并将所有的事件文件保存在logs文件夹中 writer SummaryWriter(logs)使用add…

完整版订单超时自动取消功能

前几天对实习还是继续学习技术产生了抉择&#xff0c;问了一个前辈&#xff0c;他抛给我一个问题&#xff0c;怎么做15分钟订单自动取消&#xff0c;我说然后到时间之后&#xff0c;自动执行这个订单关闭业务&#xff0c;比如把锁了的库存给解开等等操作&#xff0c;然后在数据…

【算法篇】哈希类(笔记)

目录 一、常见的三种哈希结构 二、LeetCode 练习 1. 有效的字母异位词 2. 两个数组的交集 3. 快乐数 4. 两数之和 5. 四数相加II 6. 赎金信 7. 三数之和 8. 四数之和 一、常见的三种哈希结构 当想使用哈希法来解决问题的时候&#xff0c;一般会选择如下三种数据…

4.接口测试基础(Jmter工具/场景二:一个项目由多个人负责接口测试,我只负责其中三个模块,协同)

一、场景二&#xff1a;一个项目由多个人负责接口测试&#xff0c;我只负责其中三个模块&#xff0c;协同 1.什么是测试片段&#xff1f; 1&#xff09;就相当于只是项目的一部分用例&#xff0c;不能单独运行&#xff0c;必须要和控制器&#xff08;include,模块&#xff09;一…

C++——哈希unordered_set/unordered_map的封装

目录 前言 二、unordered_set的封装 1.模板参数列表的改造 2. 增加迭代器操作 3. 模板参数的意义 三、unordered_map的封装 1、“轮子所需要的参数 2、迭代器 四、完整代码 1、HashTable 2、unordered_set 3、unordered_map 总结 前言 unordered_set和map的介绍在上一篇博客有…

2、.Net 前端框架:ASP.Net Core - .Net宣传系列文章

ASP.NET Core 是一个跨平台、高性能、开源的框架&#xff0c;用于构建现代化的、基于云的、互联网连接的应用程序。它是微软对原始ASP.NET框架的重构和扩展&#xff0c;提供了更多的灵活性和改进的性能。ASP.NET Core 可以用于开发Web应用程序、Web API、以及服务端渲染的Web页…

windows系统docker装milvus向量数据库

首先创建一个文件夹比如milvus,在创建如下文件 docker-compose.yml文件如下: version: 3.5services:etcd:container_name: milvus-etcdimage: quay.io/coreos/etcd:v3.5.5environment:- ETCD_AUTO_COMPACTION_MODErevision- ETCD_AUTO_COMPACTION_RETENTION1000- ETCD_QUOTA_B…

计算机毕业设计hadoop+spark+hive物流预测系统 物流大数据分析平台 物流信息爬虫 物流大数据 机器学习 深度学习

流程&#xff1a;1.Python爬虫采集物流数据等存入mysql和.csv文件&#xff1b;2.使用pandasnumpy或者MapReduce对上面的数据集进行数据清洗生成最终上传到hdfs&#xff1b;3.使用hive数据仓库完成建库建表导入.csv数据集&#xff1b;4.使用hive之hive_sql进行离线计算&#xff…

Qt常用控件——QComboBox

文章目录 核心属性、方法、信号模拟点餐文件加载 核心属性、方法、信号 QComboBox表示下拉框 核心属性&#xff1a; 属性说明currentText当前选中文本currentIndex当前选中的条目下标editable是否允许修改设置为true时&#xff0c;QComboBox的行为就非常接近于QLineEdit&…

【智路】智路OS Airos Edge 2.0 Quick Start

Airos Edge 2.0 Quick Start 1 智路OS2.0 1.1 简介 智路OS路侧操作系统airos-edge自下而上分别由内核层&#xff0c;硬件抽象层、框架层、服务层和应用层构成&#xff1b;提供了一系列抽象和框架&#xff0c;支持设备接入、服务、应用等组件开发&#xff0c;兼容X86和ARM操作…

【光照增强论文略读】Zero-Reference Deep Curve Estimation for Low-Light Image Enhancement

这篇题为《用于低光照图像增强的零参考深度曲线估计》的论文介绍了一种名为Zero-DCE的创新方法&#xff0c;用于增强低光照图像。其主要创新点在于&#xff0c;它在训练过程中不需要成对或非成对的参考图像&#xff0c;因此是一种“零参考”方法。通过轻量级深度学习模型DCE-Ne…

SAP学习笔记 - 开发06 - CDSView + Fiori Element 之 List Report

上一章讲了Fiori UI5开发环境搭建和实践&#xff1a; - VSCode 安装Fiori Tools插件 - SEGW 创建后台程序&#xff0c;注册服务&#xff0c;Gateway Client确认服务 - 使用SEGW公开的服务来查询数据显示到页面 SAP学习笔记 - 开发05 - Fiori UI5 开发环境搭建2 Fiori Tools…

北极星计划的回响:从Leap Motion到Midjourney的AI 3D硬件梦想

在科技的浩瀚星空中,总有一些梦想如同北极星般璀璨,指引着探索者前行。六年前,Leap Motion的CEO David以一篇充满激情的博客文章,向我们揭示了“北极星计划”——一个旨在打破数字与物理界限,创造流畅统一体验的增强现实平台。今天,随着Midjourney在AI文生图领域的全球爆…

使用OpenFeign在不同微服务之间传递用户信息时失败

文章目录 起因原因解决方法&#xff1a; 起因 从pay-service中实现下单时&#xff0c;会调用到user-service中的扣减余额。 因此这里需要在不同微服务之间传递用户信息。 但是user-service中始终从始至终拿不到user的信息。 原因 在pay-service中&#xff0c;不仅要Enable O…