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

目录

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

1.通过级联属性赋值

1)mapper

2)mapper.xml

3)测试代码

4)测试结果

2.通过标签

1)mapper

2)mapper.xml

3)测试代码

4)测试结果

3.分步查询

1)mapper

2)mapper.xml

3)测试代码

4)测试结果

附录

1)ManyToOneMapper

2)ManyToOneMapper.xml

3)ManyToOneMapperTest

4)sql

        studentSql

        classesSql


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

1.通过级联属性赋值

1)mapper

/*** 级联属性赋值*/
Student queryStudentAndClasses(int id);

2)mapper.xml

<!--级联属性赋值--><resultMap id="studentByJiLian" type="org.xiji.enty.Student"> <!--id映射--><id property="id" column="id"/><!--学生名字映射--><result property="studentName" column="studentName"/><result property="studentAge" column="studentAge"/><result property="classId" column="classId"/><!--级联赋值--><result property="classes.id" column ="classId"/><result property="classes.className" column="className"/></resultMap><select id="queryStudentAndClasses" resultMap="studentByJiLian">select * from student left join classes on student.classId = classes.id where student.id=#{id}
</select>

设置resultMap之后,使用resultMap接受查询结果,不是通过resultType接受查询结果

解释:

  1. <resultMap> 标签
    1. 定义了一个名为 studentByJiLian 的结果映射,指定其类型为 org.xiji.enty.Student。
  2. <id> 标签
    1. 映射 Student 类的 id 属性到数据库表中的 id 列。
  3. <result> 标签
    1. 映射 Student 类的 studentName、studentAge 和 classId 属性分别到数据库表中的 studentName、studentAge 和 classId 列。
  4. 级联属性映射
    1. classes 是 Student 类的一个属性,表示关联的班级信息。
    2. <result property="classes.id" column="classId"/> 映射 classes 对象的 id 属性到数据库表中的 classId 列。
    3. <result property="classes.className" column="className"/> 映射 classes 对象的 className 属性到数据库表中的 className 列。


 

3)测试代码

/*** 级联属性赋值*/
@Test
public void testManyToOne(){Student student = manyToOneMapper.queryStudentAndClasses(1);System.out.println(student.toString());}

4)测试结果

2.通过<association>标签

1)mapper

/***  association*/
Student queryStudentAndClassesByAssociation(int id);

2)mapper.xml

<!--association赋值-->
<resultMap id="associationByResultMap" type="org.xiji.enty.Student"> <!--id映射--><id property="id" column="id"/> <!--学生名字映射--><result property="studentName" column="studentName"/><result property="studentAge" column="studentAge"/><result property="classId" column="classId"/><!--association--><association property="classes" javaType="org.xiji.enty.Classes"><id property="id" column="classId"/><result property="className" column="className"/></association>
</resultMap><select id="queryStudentAndClassesByAssociation"  resultMap="associationByResultMap">select * from student left join classes on student.classId = classes.id where student.id=#{id}
</select>

设置resultMap之后,使用resultMap接受查询结果,不是通过resultType接受查询结果

解释:

  1. <resultMap> 标签
    1. 定义了一个名为 associationByResultMap 的结果映射,指定其类型为 org.xiji.enty.Student。
  2. <id> 标签
    1. 映射 Student 类的 id 属性到数据库表中的 id 列。
  3. <result> 标签
    1. 映射 Student 类的 studentName、studentAge 和 classId 属性分别到数据库表中的 studentName、studentAge 和 classId 列。
  4. <association> 标签
    1. 映射 Student 类的 classes 属性到 org.xiji.enty.Classes 类型的对象。
    2. 内部包含两个子标签:
      1. <id>:映射 Classes 类的 id 属性到数据库表中的 classId 列。
      2. <result>:映射 Classes 类的 className 属性到数据库表中的 className 列。


 

3)测试代码

/**
 * association*/
@Test
public void testManyToOneByassociation(){Student student = manyToOneMapper.queryStudentAndClassesByAssociation(2);System.out.println(student.toString());System.out.println(student.getClasses().toString());
}

4)测试结果

3.分步查询

1)mapper

/*** 分步查询*/
Student queryStudentAndClassesByStep(int id);

2)mapper.xml

<!--分步查询-->
<resultMap id="stepByResultMap" type="org.xiji.enty.Student"><id property="id" column="id"/><result property="studentName" column="studentName"/><result property="studentAge" column="studentAge"/><result property="classId" column="classId"/><association property="classes" select="queryClassesByStep" column="classId"><id property="id" column="id"/><result property="className" column="className"/></association>
</resultMap><!--第一步-->
<select id="queryStudentAndClassesByStep" resultMap="stepByResultMap" >select * from student where id=#{id}
</select>
<!--第二步-->
<select id="queryClassesByStep" resultType="org.xiji.enty.Classes">select * from classes where id=#{id}
</select>

设置resultMap之后,使用resultMap接受查询结果,不是通过resultType接受查询结果

解释:

  1. <resultMap> 标签
    1. 定义了一个名为 stepByResultMap 的结果映射,指定其类型为 org.xiji.enty.Student。
  2. 基本属性映射
    1. <id>:映射 Student 类的 id 属性到数据库表中的 id 列。
    2. <result>:映射 Student 类的 studentName、studentAge 和 classId 属性分别到数据库表中的 studentName、studentAge 和 classId 列。
  3. <association> 标签
    1. 映射 Student 类的 classes 属性到 org.xiji.enty.Classes 类型的对象。
    2. 使用 select 属性指定一个子查询语句 queryClassesByStep,该查询将根据 classId 获取班级信息。
    3. column 属性指定用于子查询的列名,这里是 classId。

3)测试代码

/*** 分步查询*/
@Test
public void testManyToOneByStep(){Student student = manyToOneMapper.queryStudentAndClassesByStep(3);System.out.println(student.toString());System.out.println(student.getClasses().toString());
}

4)测试结果

附录

1)ManyToOneMapper

package org.xiji.mapper;import org.apache.ibatis.annotations.Mapper;
import org.xiji.enty.Student;@Mapper
public interface ManyToOneMapper {/*** 级联属性赋值*/Student queryStudentAndClasses(int id);/***  association*/Student queryStudentAndClassesByAssociation(int id);/*** 分步查询*/Student queryStudentAndClassesByStep(int id);}

2)ManyToOneMapper.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.ManyToOneMapper"><!--级联属性赋值--><resultMap id="studentByJiLian" type="org.xiji.enty.Student"><!--id映射--><id property="id" column="id"/><!--学生名字映射--><result property="studentName" column="studentName"/><result property="studentAge" column="studentAge"/><result property="classId" column="classId"/><!----><result property="classes.id" column ="classId"/><result property="classes.className" column="className"/></resultMap><select id="queryStudentAndClasses" resultMap="studentByJiLian">select * from student left join classes on student.classId = classes.id where student.id=#{id}</select><!--association赋值--><resultMap id="associationByResultMap" type="org.xiji.enty.Student"><!--id映射--><id property="id" column="id"/><!--学生名字映射--><result property="studentName" column="studentName"/><result property="studentAge" column="studentAge"/><result property="classId" column="classId"/><!--association--><association property="classes" javaType="org.xiji.enty.Classes"><id property="id" column="classId"/><result property="className" column="className"/></association></resultMap><select id="queryStudentAndClassesByAssociation"  resultMap="associationByResultMap">select * from student left join classes on student.classId = classes.id where student.id=#{id}</select><!--分步查询--><resultMap id="stepByResultMap" type="org.xiji.enty.Student"><id property="id" column="id"/><result property="studentName" column="studentName"/><result property="studentAge" column="studentAge"/><result property="classId" column="classId"/><association property="classes" select="queryClassesByStep" column="classId"><id property="id" column="id"/><result property="className" column="className"/></association></resultMap><!--第一步--><select id="queryStudentAndClassesByStep" resultMap="stepByResultMap" >select * from student where id=#{id}</select><!--第二步--><select id="queryClassesByStep" resultType="org.xiji.enty.Classes">select * from classes where id=#{id}</select></mapper>

3)ManyToOneMapperTest

import org.apache.ibatis.annotations.Mapper;
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.Student;
import org.xiji.mapper.ManyToOneMapper;@SpringJUnitConfig(locations = {"classpath:springConfig.xml"})
public class ManyToOneMapperTest {@Autowiredprivate ManyToOneMapper manyToOneMapper;/*** 级联属性赋值*/@Testpublic void testManyToOne(){Student student = manyToOneMapper.queryStudentAndClasses(1);System.out.println(student.toString());}/*** association*/@Testpublic void testManyToOneByassociation(){Student student = manyToOneMapper.queryStudentAndClassesByAssociation(2);System.out.println(student.toString());System.out.println(student.getClasses().toString());}/*** 分步查询*/@Testpublic void testManyToOneByStep(){Student student = manyToOneMapper.queryStudentAndClassesByStep(3);System.out.println(student.toString());System.out.println(student.getClasses().toString());}}

4)sql

        studentSql

SET NAMES utf8mb4;
SET FOREIGN_KEY_CHECKS = 0;-- ----------------------------
-- Table structure for student
-- ----------------------------
DROP TABLE IF EXISTS `student`;
CREATE TABLE `student`  (`id` 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 (`id`) USING BTREE,INDEX `classId`(`classId` ASC) USING BTREE,CONSTRAINT `classId` FOREIGN KEY (`classId`) REFERENCES `classes` (`id`) 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

SET NAMES utf8mb4;
SET FOREIGN_KEY_CHECKS = 0;-- ----------------------------
-- Table structure for classes
-- ----------------------------
DROP TABLE IF EXISTS `classes`;
CREATE TABLE `classes`  (`id` int NOT NULL AUTO_INCREMENT COMMENT '班级id',`className` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NULL DEFAULT NULL COMMENT '班级名称',PRIMARY KEY (`id`) 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/140624.html

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

相关文章

Golang | Leetcode Golang题解之第405题数字转换为十六进制数

题目&#xff1a; 题解&#xff1a; func toHex(num int) string {if num 0 {return "0"}sb : &strings.Builder{}for i : 7; i > 0; i-- {val : num >> (4 * i) & 0xfif val > 0 || sb.Len() > 0 {var digit byteif val < 10 {digit 0…

kettle从入门到精通 第八十五课 ETL之kettle kettle中javascript步骤调用外部javascript/js文件

场景&#xff1a;交流学习群里面有小伙伴咨询kettle中的javascript代码步骤如何调用外部js文件中的函数&#xff0c;觉得有点意思的&#xff0c;于是就抽时间整理了一下。 1、外部js文件为test.js&#xff0c;代码如下&#xff1a; function test(param){return "接收到了…

估值1500亿美元!OpenAI据称正洽谈新一轮融资 | LeetTalk Daily

“LeetTalk Daily”&#xff0c;每日科技前沿&#xff0c;由LeetTools AI精心筛选&#xff0c;为您带来最新鲜、最具洞察力的科技新闻。 OpenAI作为全球领先的人工智能研究机构之一&#xff0c;近期宣布计划以1500亿美元的投前估值融资65亿美元&#xff0c;这一消息引发了广泛的…

【Git】常见命令(仅笔记)

文章目录 创建/初始化本地仓库添加本地仓库配置项提交文件查看仓库状态回退仓库查看日志分支删除文件暂存工作区代码远程仓库使用 .gitigore 文件让 git 不追踪一些文件标签 创建/初始化本地仓库 git init添加本地仓库配置项 git config -l #以列表形式显示配置项git config …

电脑连手机热点,上不了网

打开适配器设置 双击打开

【若依RuoYi-Vue | 项目实战】帝可得后台管理系统(一)

文章目录 一、项目背景介绍1、什么是帝可得&#xff1f;2、物联网3、售货机术语4、角色与功能5、业务流程&#xff08;1&#xff09;平台管理员&#xff08;2&#xff09;运维人员&#xff08;3&#xff09;运营人员&#xff08;4&#xff09;消费者 6、产品原型7、库表设计 二…

【笔记】CCF直播:《如何在国际会议上有效交流》(2024-9-15)

目录 一、提问的勇气二、提问什么三、其他主题的报告为什么听四、会议前怎么读大量论文&#xff1f;五、workshop为什么参加&#xff1f;Poster环节&#xff1f;六、提问环节七、其他 今天听了《如何在国际会议上有效交流》的直播讲座&#xff0c;记录一些笔记。 一、提问的勇…

SQL进阶技巧:火车票相邻座位预定一起可能情况查询算法 ?

目录 0 场景描述 1 数据准备 2 问题分析 2.1 分析函数法 2.2 自关联求解 3 小结 如果觉得本文对你有帮助&#xff0c;那么不妨也可以选择去看看我的数字化建设通关指南博客专栏 &#xff0c;或许对你更有用。专栏原价99&#xff0c;现在活动价29.9&#xff0c;按照阶梯…

COSMOSPANDA星际熊猫助阵长江商学院高尔夫周年庆典

在金秋送爽的美好时节&#xff0c;星际漫游&#xff08;广州&#xff09;品牌管理有限公司旗下备受欢迎的潮玩IP“COSMOSPANDA星际熊猫”与长江商学院深圳校友会强强联手&#xff0c;于9月10日在风景如画的中山雅居乐长江高尔夫球会成功举办了“长江商学院深圳校友会高尔夫球队…

论文速递!Knowledge-driven+Informer! 联合知识和数据驱动的混合模型,用于NOx排放浓度预测

论文标题&#xff1a;Prediction of NOx emission concentration from coal-fired power plant based on joint knowledge and data driven 期刊信息&#xff1a;Energy (中科院1区, JCR Q1 TOP, IF9) 引用&#xff1a;Wu Z, Zhang Y, Dong Z. Prediction of NOx emission co…

【Android Studio】API 29(即Android 10)或更高版本,在程序启动时检查相机权限,并在未获取该权限时请求它

文章目录 1. 在AndroidManifest.xml文件中&#xff0c;声明相机权限&#xff1a;2. 在你的Activity中&#xff08;例如MainActivity&#xff09;测试 1. 在AndroidManifest.xml文件中&#xff0c;声明相机权限&#xff1a; <uses-feature android:name"android.hardwar…

win11下面graphviz的用法

安装 安装graphviz 2.38版本 控制面板在变量path中增加E:\software\Graphviz\bin example.dot代码 digraph SignalPathway {node [fontname"SimHei"];edge [fontname"SimHei"];// 定义节点形状node [shapecircle];// 定义节点CellA [label"细胞 A&…

【Elasticsearch系列五】Java API

&#x1f49d;&#x1f49d;&#x1f49d;欢迎来到我的博客&#xff0c;很高兴能够在这里和您见面&#xff01;希望您在这里可以感受到一份轻松愉快的氛围&#xff0c;不仅可以获得有趣的内容和知识&#xff0c;也可以畅所欲言、分享您的想法和见解。 推荐:kwan 的首页,持续学…

Autosar E2E通信保护简介

文章目录 前言一、E2E基本概念二、为什么要做E2E?三、E2E保护的三种不同实现方式E2E TransformerE2E Protection Wrapper(E2EPW)COM E2E Callout四、E2E ProfileE2E Profile 01 机制E2E Profile 02 机制E2E Profile 04 机制E2E Profile 05 机制E2E Profile 06 机制E2E Profi…

《微信小程序实战(1)· 开篇示例 》

&#x1f4e2; 大家好&#xff0c;我是 【战神刘玉栋】&#xff0c;有10多年的研发经验&#xff0c;致力于前后端技术栈的知识沉淀和传播。 &#x1f497; &#x1f33b; CSDN入驻不久&#xff0c;希望大家多多支持&#xff0c;后续会继续提升文章质量&#xff0c;绝不滥竽充数…

深入理解SpringBoot(一)----SpringBoot的启动流程分析

1、SpringApplication 对象实例化 SpringApplication 文件 public static ConfigurableApplicationContext run(Object[] sources, String[] args) {// 传递的source其实就是类Bootstrapreturn new SpringApplication(sources).run(args);// 实例化一个SpringApplication对象执…

豆包MarsCode | 一款智能编程助手开发工具

豆包MarsCode | 一款智能编程助手开发工具 豆包MarsCode 是基于豆包大模型的智能开发工具&#xff0c;提供 Cloud IDE 和 AI 编程助手&#xff0c;支持代码补全、智能问答、代码解释与修复&#xff0c;兼容主流编程工具与 100 种编程语言&#xff0c;助力编程更智能便捷 豆包 M…

Cyber Weekly #24

赛博新闻 1、OpenAI发布最强模型o1 本周四&#xff08;9月12日&#xff09;&#xff0c;OpenAI宣布推出OpenAIo1系列模型&#xff0c;标志着AI推理能力的新高度。o1系列包括性能强大的o1以及经济高效的o1-mini&#xff0c;适用于不同复杂度的推理任务。新模型在科学、编码、数…

SEGGERS实时系统embOS推出Linux端模拟器

SEGGER 发布了两个新的 embOS 仿真模拟器&#xff1a;embOS Sim Linux 和 embOS-MPU Sim Linux。 通过模拟 Linux 主机系统上的硬件&#xff0c;取代物理硬件&#xff0c;为开发人员提供了一种无缝的方式来构建原型和测试应用程序。 embOS Sim Linux 端口支持 32 位和 64 位系…

【大模型专栏—进阶篇】智能对话全总结

大模型专栏介绍 &#x1f60a;你好&#xff0c;我是小航&#xff0c;一个正在变秃、变强的文艺倾年。 &#x1f514;本文为大模型专栏子篇&#xff0c;大模型专栏将持续更新&#xff0c;主要讲解大模型从入门到实战打怪升级。如有兴趣&#xff0c;欢迎您的阅读。 &#x1f4…