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.mzph.cn/web/53031.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

【C++二叉树】102.二叉树的层序遍历

107. 二叉树的层序遍历 II - 力扣&#xff08;LeetCode&#xff09; 思路分析&#xff1a; 层序遍历&#xff0c;但是要注意输出的结果是一个二维数组&#xff0c;不是一层一个值一个值的输出&#xff0c;而是要一层一层的输出。可以通过一个循环控制每一层的数据个数&#xff…

PyCharm 安装教程

传送门 PyCharm 是一款由 JetBrains 开发的强大的 Python 集成开发环境&#xff08;IDE&#xff09;。它支持多种功能&#xff0c;包括调试、代码补全、智能代码分析、版本控制集成等&#xff0c;特别适合开发 Python 项目。接下来&#xff0c;我们将详细介绍如何在不同操作系…

【C++高阶】解锁C++的深层魅力——探索特殊类的奥秘

&#x1f4dd;个人主页&#x1f339;&#xff1a;Eternity._ ⏩收录专栏⏪&#xff1a;C “ 登神长阶 ” &#x1f921;往期回顾&#x1f921;&#xff1a;C 类型转换 &#x1f339;&#x1f339;期待您的关注 &#x1f339;&#x1f339; ❀C特殊类 &#x1f4d2;1. 不能被拷贝…

文字loading加载

效果 1. 导入库 import sys from PyQt5.QtCore import QTimer, Qt, QThread, pyqtSignal from PyQt5.QtGui import QPainter, QFont, QColor, QBrush from PyQt5.QtWidgets import QApplication, QWidget, QVBoxLayout, QPushButton, QProgressBar, QLabel 代码首先导入了P…

C++ | Leetcode C++题解之第409题最长回文串

题目&#xff1a; 题解&#xff1a; class Solution { public:int longestPalindrome(string s) {unordered_map<char, int> count;int ans 0;for (char c : s)count[c];for (auto p : count) {int v p.second;ans v / 2 * 2;if (v % 2 1 and ans % 2 0)ans;}retur…

【设计模式-外观】

这里写自定义目录标题 定义UML图角色作用代码使用场景 定义 为子系统中一组相关接口提供一致界面&#xff0c;定义一个高级接口&#xff0c;使得子系统更加容易使用。 UML图 角色作用 外观&#xff08;Facade&#xff09;角色&#xff1a;这是外观模式的核心&#xff0c;它知…

macOS上谷歌浏览器的十大隐藏功能

谷歌浏览器&#xff08;Google Chrome&#xff09;在macOS上拥有一系列强大而隐蔽的特性&#xff0c;这些功能能显著提高您的浏览体验。从多设备同步到提升安全性和效率&#xff0c;这些被低估的功能等待着被发掘。我们将逐步探索这些功能&#xff0c;帮助您最大化利用谷歌浏览…

力扣题解815

大家好&#xff0c;欢迎来到无限大的频道。祝大家中秋节快乐​。 今日继续给大家带来力扣题解。 题目描述&#xff08;困难&#xff09;​&#xff1a; 公交路线 给你一个数组 routes &#xff0c;表示一系列公交线路&#xff0c;其中每个 routes[i] 表示一条公交线路&…

Python logging库(python日志库)Logger(记录器、收集器、采集器)、Handler(处理器)、Formatter(格式化器)、Log Level(日志级别)

文章目录 Python Logging库详解简介日志记录的基本概念1. Logger&#xff08;记录器&#xff09;&#xff1a;这是日志系统的入口点。每个记录器都有一个名称&#xff0c;并且记录器之间可以存在父子关系。2. Handler&#xff08;处理器&#xff09;&#xff1a;记录器将日志消…

网络安全-intigriti-0422-XSS-Challenge Write-up

目录 一、环境 二、解题 2.1看源码 一、环境 Intigriti April Challenge 二、解题 要求&#xff1a;弹出域名就算成功 2.1看源码 我们看到marge方法&#xff0c;肯定是原型链污染题目 接的是传参&#xff0c;我们可控的点在于qs.config和qs.settings&#xff0c;这两个可…

Java设计模式—面向对象设计原则(四) ----->接口隔离原则(ISP) (完整详解,附有代码+案例)

文章目录 3.4 接口隔离原则(ISP)3.4.1 概述3.4.2 案列 3.4 接口隔离原则(ISP) 接口隔离原则&#xff1a;Interface Segregation Principle&#xff0c;简称ISP 3.4.1 概述 客户端测试类不应该被迫依赖于它不使用的方法&#xff1b;一个类对另一个类的依赖应该建立在最小的接…

Invoke-Maldaptive:一款针对LDAP SearchFilter的安全分析工具

关于Invoke-Maldaptive MaLDAPtive 是一款针对LDAP SearchFilter的安全分析工具&#xff0c;旨在用于对LDAP SearchFilter 执行安全解析、混淆、反混淆和安全检测。 其基础是 100% 定制的 C# LDAP 解析器&#xff0c;该解析器处理标记化和语法树解析以及众多自定义属性&#x…

Excel图片批量插入单元格排版处理插件【图片大师】

为了方便大家在图片的插入排版的重复工作中解放出来&#xff0c;最近发布了一款批量插入图片的插件&#xff0c;欢迎大家下载&#xff0c;免费试用。 这是图片的文件夹&#xff1a; 主要功能如下: 1&#xff0c;匹配单元格名称的多张图批量插入到一个单元格 该功能支持设置图…

腾讯百度阿里华为常见算法面试题TOP100(4):双指针、哈希、滑动窗口

之前总结过字节跳动TOP50算法面试题&#xff1a; 字节跳动常见算法面试题top50整理_沉迷单车的追风少年-CSDN博客_字节算法面试题 目录 双指针 42.接雨水 283.移动零 11.盛最多水的容器 15.三数之和 哈希 1. 两数之和 49.字母异位词分组 128.最长连续序列 滑动窗…

网络协议全景:Linux环境下的TCP/IP、UDP

目录 1.UDP协议解析1.1.定义1.2.UDP报头1.3.特点1.4.缓冲区 2.TCP协议解析2.1.定义2.2.报头解析2.2.1.首部长度&#xff08;4位&#xff09;2.2.2.窗口大小2.2.3.确认应答机制2.2.4.6个标志位 2.3.超时重传机制2.4.三次握手四次挥手2.4.1.全/半连接队列2.4.2.listen2.4.3.TIME_…

SQL进阶的技巧:如何实现某列的累计乘积?

目录 0 场景描述 1 数据准备 2 问题分析 3 完全情况查询 4 小结 0 场景描述 在做数据处理的时候,尤其是复利累积的时候,有时候会有这样一场景,通过某种条件找到一列数据[X1,X2,X3...Xn],然后想要求y=X1X2X3...Xn。下面给出一个具体案例来详细解释这一问题,如下图所示…

学成在线练习(HTML+CSS)

准备工作 项目目录 内部包含当前网站的所有素材&#xff0c;包含 HTML、CSS、图片、JavaScript等等 1.由于元素具有一些默认样式&#xff0c;可能是我们写网页过程中根本不需要的&#xff0c;所有我们可以在写代码之前就将其清除 base.css /* 基础公共样式&#xff1a;清除…

大模型入门3:理解LLAMA

LLama在transformers库中的代码&#xff0c;以及各部分原理Llama3.1技术报告LLama 33b 微调尝试 Model a stack of DecoderBlocks(SelfAttention, FeedForward, and RMSNorm) decoder block 整体结构&#xff1a;最大的区别在pre-norm x -> norm(x) -> attention() -…

什么是上拉,下拉?

上拉就是将引脚通过一个电阻连接到电源&#xff0c;作用&#xff1a;1.使IO口的不确定电平稳定在高点平&#xff0c;2、为了增加IO口拉电流的能力。 下拉就是将引脚通过一个电阻与GND相连&#xff0c;作用&#xff1a;1.从器件输出电流 2.当IO口为输入状态时&#xff0c;引脚的…

【爱给网-注册安全分析报告-无验证方式导致安全隐患】

前言 由于网站注册入口容易被黑客攻击&#xff0c;存在如下安全问题&#xff1a; 1. 暴力破解密码&#xff0c;造成用户信息泄露 2. 短信盗刷的安全问题&#xff0c;影响业务及导致用户投诉 3. 带来经济损失&#xff0c;尤其是后付费客户&#xff0c;风险巨大&#xff0c;造…