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

news2024/9/24 15:24:40

目录

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 mapper
        PUBLIC "-//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 {

    @Autowired
    private ManyToOneMapper manyToOneMapper;

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

    }

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

    /**
     * 分步查询
     */
    @Test
    public 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.coloradmin.cn/o/2138486.html

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

相关文章

【技术调研】三维(4)-ThreeJs阴影投射、光线投射及案例

阴影投射 阴影是灯光经过物体后产生的&#xff0c;几个关键的设置&#xff1a; 灯光属性设置&#xff1a;.castShadow : Boolean 。此属性设置为 true 灯光将投射阴影。注意&#xff1a;这样做的代价比较高&#xff0c;需要通过调整让阴影看起来正确。 查看 DirectionalLight…

STM32(十四):USART串口数据包

HEX数据包 0xFF包头&#xff0c;0xFE包尾。 如果数据和包头包尾重复&#xff0c;可能会引起误判。 解决办法&#xff1a; 1. 限制载荷数据的范围 2. 如果无法避免载荷数据和包头包尾重复&#xff0c;就使用尽量使用固定长度数据包。 包头 ‘\r\n 包尾 在载荷数据中间可以出现…

代码23. 合并 K 个升序链表

模拟面试的时候没做出来&#xff0c;心碎了。 题目链接 . - 力扣&#xff08;LeetCode&#xff09; 自己的思考 无思考&#xff0c;直接看答案吧。 正确答案 其实写还是自己写的&#xff0c;看了下题解的思路。 第一种 思路简单&#xff0c;两两合并&#xff0c;注意事项已…

李飞飞任CEO,空间智能公司World Labs亮相,全明星阵容曝光

人工智能的下个大方向已经出现&#xff0c;标志性学者决定下场创业。 本周五&#xff0c;一个重磅消息引爆了 AI 圈&#xff1a;斯坦福大学计算机科学家李飞飞正式宣布创办 AI 初创公司 ——World Labs&#xff0c;旨在向人工智能系统传授有关物理现实的深入知识。 李飞飞说道&…

【检索快,IEEE独立出版】2024年第四届电子信息工程与计算机科学国际会议(EIECS 2024)

大会简介&#xff1a; 2024年第四届电子信息工程与计算机科学国际会议&#xff08;EIECS 2024&#xff09;将于2024年9月27日至29日在中国延吉举行。会议由长春理工大学主办&#xff0c;延边大学、长春理工大学电子信息工程学院、长春理工大学计算机科学技术学院、长春理工大学…

数据结构——栈和队列(栈的顺序存储结构和链式存储结构)

栈的定义 栈是一种重要的线性结构&#xff0c;可以这样讲&#xff0c;栈是前面讲过的线性表的一种具体形式。就像我们刚才的例子&#xff0c;栈这种后进先出的数据结构应用是非常广泛的。在生活中&#xff0c;例如我们的浏览器&#xff0c;每次点击一次“后退”都是退回到最近…

数据库密钥管理的密钥生成

数据库密钥管理是指对数据库中使用的加密密钥进行的一系列安全操作&#xff0c;以确保数据的机密性、完整性和可用性。这一管理过程通常包括密钥的生成、存储、分发、使用和销毁等环节。以下是关于数据库密钥管理的详细解析&#xff1a; 一、密钥的生成 目的&#xff1a;生成用…

谷歌图像生成AI-imagen 3新手入门指南!

1Google 最近推出了 Imagen 3&#xff0c;这是目前为止其最先进的文本生成图像模型。它基于之前的版本进行了改进&#xff0c;提供了更加精确的图像生成&#xff0c;减少了图像中的瑕疵&#xff0c;能够生成逼真、栩栩如生的图像。相比于早期版本&#xff0c;Imagen 3 可以处理…

Linux:重定向以及管道

重定向&#xff08;重新定向命令的输出&#xff09; 将前面命令的输出&#xff0c;作为内容&#xff0c;写入到后面的文件 管道 管道&#xff08;操作符号 | &#xff09; 作用&#xff1a;将前面命令的输出&#xff0c;传递给后面命令&#xff0c;作为后面命令的参数…

通信工程学习:什么是SNI业务节点接口

SNI&#xff1a;业务节点接口 SNI业务节点接口&#xff0c;全称Service Node Interface&#xff0c;是接入网&#xff08;AN&#xff09;和一个业务节点&#xff08;SN&#xff09;之间的接口&#xff0c;位于接入网的业务侧。这一接口在通信网络中扮演着重要的角色&#xff0c…

【机器学习-四-无监督学习unsupervise learning-聚类算法简介】

无监督学习unsupervise learning 聚类聚类的过程相似度度量方法聚类的方法划分式层次聚类基于密度的聚类 上一节讲的无监督学习&#xff0c;但是很多人可能会很疑惑&#xff0c;没有目标&#xff0c;那算法是怎么学会该怎样分类的呢&#xff1f;今天就简介一下其中的聚类算法。…

使用 SpringBoot 基础web开发的支持

首先导入项目相关的依赖&#xff1a; pom.xml 文件&#xff1a; 导入相关项目依赖 <?xml version"1.0" encoding"UTF-8"?> <project xmlns"http://maven.apache.org/POM/4.0.0" xmlns:xsi"http://www.w3.org/2001/XMLSchema-in…

句子成分——每日一划(八)

目录 一、原句 二、第一部分 三、第二部分 一、原句 In class society everyone lives as a member of a particular class, and every kind of thinking, without exception, is stamped with the brand of a class. 来源&#xff1a;二、阶级和阶级斗争 二、第一部分 In…

免费像素画绘制软件 | Pixelorama v1.0.3

Pixelorama 是一款开源像素艺术多工具软件&#xff0c;旨在为用户提供一个强大且易于使用的平台来创作各种像素艺术作品&#xff0c;包括精灵、瓷砖和动画。这款软件以其丰富的工具箱、动画支持、像素完美模式、剪裁遮罩、预制及可导入的调色板等特色功能&#xff0c;满足了像素…

凑数字dp解决

前言&#xff1a;没有想到这个题目可以用dp来做&#xff0c;我们之前能够达到的最大的数字 当前的这一个数字为当前最大的数 ‘题目地址 #include<bits/stdc.h> using namespace std;#define int long long const int N (int)1e510;signed main() {int t; cin >>…

[全网首发]怎么让国行版iPhone使用苹果Apple Intelligence

全文共分为两个部分&#xff1a;第一让苹果手机接入AI&#xff0c;第二是让苹果手机接入ChatGPT 4o功能。 一、国行版iPhone开通 Apple Intelligence教程 打破限制&#xff1a;让国行版苹果手机也能接入AI 此次发布会上&#xff0c;虽然国行 iPhone16 系列不支持 GPT-4o&…

【Vue】2

1 Vue 生命周期 Vue生命周期&#xff1a;一个 Vue 实例从 创建 到 销毁 的整个过程 创建(create)阶段&#xff1a;组件实例化时&#xff0c;初始化数据、事件、计算属性等挂载(mount)阶段&#xff1a;将模板渲染并挂载到 DOM 上更新(update)阶段&#xff1a;当数据发生变化时…

Qt:饿汉单例(附带单例使用和内存管理)

前言 本文主要写饿汉单例以及单例的释放&#xff0c;网上很多教程只有单例的创建&#xff0c;但是并没有告诉我们单例的内存管理&#xff0c;这就很头疼。 正文 饿汉式单例 // SingletonClass.h #ifndef SINGLETONCLASS_H #define SINGLETONCLASS_H #include <QObject&g…

【Android Studio】使用雷电模拟器调试

文章目录 进入开发者模式使雷电模拟器adb连接PC测试 进入开发者模式 多次点击版本号 -开区USB调试 使雷电模拟器adb连接PC 写cmd脚本 雷电模拟器端口为5555 &#xff0c;脚本内容如下&#xff1a; adb.exe connect 127.0.0.1:5555双击bat脚本文件 测试

华为应用权限初次申请及二次申请

应用权限概述 系统提供了一种允许应用访问系统资源&#xff08;如&#xff1a;通讯录等&#xff09;和系统能力&#xff08;如&#xff1a;访问摄像头、麦克风等&#xff09;的通用权限访问方式&#xff0c;来保护系统数据&#xff08;包括用户个人数据&#xff09;或功能&…