当前位置: 首页 > news >正文

快速了解MyBatis---映射关系多对一

文章目录

  • 映射关系多对一
    • 映射关系-官方文档
    • 映射关系多对1-基本介绍
      • 基本介绍
      • 注意细节
    • 映射关系多对1-映射方式
      • 映射方式
      • 配置Mapper.xml 方式-应用实例
      • 注解实现多对1 映射-应用实例

映射关系多对一

映射关系-官方文档

文档地址: https://mybatis.org/mybatis-3/zh/sqlmap-xml.html

映射关系多对1-基本介绍

基本介绍

  1. 项目中多对1 的关系是一个基本的映射关系, 多对1, 也可以理解成是1 对多.
  2. User — Pet: 一个用户可以养多只宠物
  3. Dep —Emp : 一个部门可以有多个员工

注意细节

  1. 我们直接讲双向的多对一的关系,单向的多对一比双向的多对一简单。
  2. 在实际的项目开发中, 要求会使用双向的多对一的映射关系
  3. 什么是双向的多对一的关系: 比如通过User 可以查询到对应的Pet, 反过来,通过Pet 也可以级联查询到对应的User 信息.
  4. 多对多的关系,是在多对1 的基础上扩展.

映射关系多对1-映射方式

映射方式

方式1:通过配置XxxMapper.xml 实现多对1

方式2:通过注解的方式实现多对1

配置Mapper.xml 方式-应用实例

需求说明: 实现级联查询,通过user 的id 可以查询到用户信息,并可以查询到关联的pet信息,

​ 反过来,通过Pet 的id 可以查询到Pet 的信息,并且可以级联查询到它的主人User对象信息。

  1. 创建mybatis_user 和mybatis_pet 表
CREATE TABLE mybatis_user
(id INT PRIMARY KEY AUTO_INCREMENT,NAME VARCHAR(32) NOT NULL DEFAULT ''
)CHARSET=utf8 ;CREATE TABLE mybatis_pet
(id INT PRIMARY KEY AUTO_INCREMENT,nickname VARCHAR(32) NOT NULL DEFAULT '',user_id INT ,FOREIGN KEY (user_id) REFERENCES mybatis_user(id)
)CHARSET=utf8 ;INSERT INTO mybatis_user
VALUES(NULL,'宋江'),(NULL,'张飞');
INSERT INTO mybatis_pet
VALUES(1,'黑背',1),(2,'小哈',1);
INSERT INTO mybatis_pet
VALUES(3,'波斯猫',2),(4,'贵妃猫',2);SELECT * FROM mybatis_user;
SELECT * FROM mybatis_pet;

image-20230731145051413

  1. 创建src\main\java\com\nlc\entity\Pet.java
public class Pet {private Integer id;private String nickname;//一个pet对应一个主人 User对象private User user;public Integer getId() {return id;}public void setId(Integer id) {this.id = id;}public String getNickname() {return nickname;}public void setNickname(String nickname) {this.nickname = nickname;}public User getUser() {return user;}public void setUser(User user) {this.user = user;}}

创建src\main\java\com\nlc\entity\User.java

public class User {private Integer id;private String name;//因为一个user可以养多个宠物,mybatis 使用集合List<Pet>体现这个关系private List<Pet> pets;public Integer getId() {return id;}public void setId(Integer id) {this.id = id;}public String getName() {return name;}public void setName(String name) {this.name = name;}public List<Pet> getPets() {return pets;}public void setPets(List<Pet> pets) {this.pets = pets;}//这toString会带来麻烦=>会造成StackOverFlow//@Override//public String toString() {//    return "User{" +//            "id=" + id +//            ", name='" + name + '\'' +//            ", pets=" + pets +//            '}';//}
}
  1. 创建PetMapper.java

    public interface PetMapper {//通过User的id来获取pet对象,可能有多个,因此使用List接收public List<Pet> getPetByUserId(Integer userId);//通过pet的id获取Pet对象, 同时会查询到pet对象关联的user对象public Pet getPetById(Integer id);
    }
    

    创建UserMapper.java

public interface UserMapper {//通过id获取User对象public User getUserById(Integer id);}
  1. 创建UserMapper.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 nameNlcace="com.nlc.mapper.UserMapper"><!--解读1、一定要想一想我们前面1-1是如何实现2、配置/实现 public User getUserById(Integer id);3、思路(1) 先通过user-id 查询得到user信息 (2) 再根据user-id查询对应的pet信息并映射到User-List<Pet> pets--><resultMap id="UserResultMap" type="User"><id property="id" column="id"/><result property="name" column="name"/><!--解读:因为pets属性是集合,因此这里需要是collection标签来处理1. ofType="Pet" 指定返回的集合中存放的数据类型Pet2. collection 表示 pets 是一个集合3. property="pets" 是返回的user对象的属性 pets4. column="id" SELECT * FROM `mybatis_user` WHERE `id` = #{id} 返回的id字段对应的值--><collection property="pets" column="id" ofType="Pet"select="com.nlc.mapper.PetMapper.getPetByUserId"/></resultMap><select id="getUserById" parameterType="Integer" resultMap="UserResultMap">SELECT * FROM `mybatis_user` WHERE `id` = #{id}</select></mapper>
    
  2. 创建PetMapper.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 nameNlcace="com.nlc.mapper.PetMapper"><!--1、通过User的id来获取pet对象,可能有多个,因此使用List接收2、public List<Pet> getPetByUserId(Integer userId);3. 完成的思路和前面大体相同.--><resultMap id="PetResultMap" type="Pet"><id property="id" column="id"/><result property="nickname" column="nickname"/><association property="user" column="user_id"select="com.nlc.mapper.UserMapper.getUserById" /></resultMap><select id="getPetByUserId" parameterType="Integer" resultMap="PetResultMap">SELECT * FROM `mybatis_pet` WHERE `user_id` = #{userId}</select><!--说明1. 注意体会resultMap带来好处, 直接复用2. 实现/配置public Pet getPetById(Integer id);3. 通过pet的id获取Pet对象--><select id="getPetById"  parameterType="Integer"  resultMap="PetResultMap">SELECT * FROM `mybatis_pet` WHERE `id` = #{id}</select>
</mapper>
  1. 创建PetMapperTest.java 完成测试

    public class PetMapperTest {//属性private SqlSession sqlSession;private PetMapper petMapper;//初始化@Beforepublic void init() {//获取到sqlSessionsqlSession = MyBatisUtils.getSqlSession();petMapper = sqlSession.getMapper(PetMapper.class);}@Testpublic void getPetByUserId() {List<Pet> pets = petMapper.getPetByUserId(2);for (Pet pet : pets) {System.out.println("pet信息-" + pet.getId() + "-" + pet.getNickname());User user = pet.getUser();System.out.println("user信息 name-" + user.getName());}if(sqlSession != null) {sqlSession.close();}}@Testpublic void getPetById() {Pet pet = petMapper.getPetById(2);System.out.println("pet信息-" + pet.getId() + "-" + pet.getNickname());User user = pet.getUser();System.out.println("user信息-" + user.getId() + "-" + user.getName());if(sqlSession != null) {sqlSession.close();}}
    }
    
  2. 创建UserMapperTest.java 完成测试

    public class UserMapperTest {//属性private SqlSession sqlSession;private UserMapper userMapper;//初始化@Beforepublic void init() {//获取到sqlSessionsqlSession = MyBatisUtils.getSqlSession();userMapper = sqlSession.getMapper(UserMapper.class);}@Testpublic void getUserById() {User user = userMapper.getUserById(2);System.out.println("user信息-" + user.getId() + "-" + user.getName());List<Pet> pets = user.getPets();for (Pet pet : pets) {System.out.println("养的宠物信息-" + pet.getId() + "-" + pet.getNickname());}if(sqlSession != null) {sqlSession.close();}}
    }
    

注解实现多对1 映射-应用实例

需求说明: 通过注解的方式来实现下面的多对1 的映射关系,实现级联查询,

完成前面完成的任务,通过User–>Pet 也可Pet->User , 在实际开发中推荐使用配置方式来做

  1. 创建UserMapperAnnotation.java
// UserMapperAnnotation:以注解的方式来配置多对一
public interface UserMapperAnnotation {//通过id获取User对象/*** 1. 注解的配置就是对应的Mapper.xml文件配置的,改写* 2.*     1、一定要想一想我们前面1-1是如何实现*     2、配置/实现 public User getUserById(Integer id);*     3、思路(1) 先通过user-id 查询得到user信息 (2) 再根据user-id查询对应的pet信息*       并映射到User-List<Pet> pets*     <resultMap id="UserResultMap" type="User">*         <id property="id" column="id"/>*         <result property="name" column="name"/>*         1. ofType="Pet" 指定返回的集合中存放的数据类型Pet*         2. collection 表示 pets 是一个集合*         3. property="pets" 是返回的user对象的属性 pets*         4. column="id" SELECT * FROM `mybatis_user` WHERE `id` = #{id} 返回的id字段对应的值*         <collection property="pets" column="id" ofType="Pet"*                     select="com.nlc.mapper.PetMapper.getPetByUserId"/>*     </resultMap>*     <select id="getUserById" parameterType="Integer" resultMap="UserResultMap">*         SELECT * FROM `mybatis_user` WHERE `id` = #{id}*     </select>*/@Select("SELECT * FROM `mybatis_user` WHERE `id` = #{id}")@Results({@Result(id = true, property = "id", column = "id"),@Result(property = "name", column = "name"),//这里注意,pets属性对应的是集合@Result(property = "pets",column = "id",many = @Many(select = "com.nlc.mapper.PetMapperAnnotation.getPetByUserId"))})public User getUserById(Integer id);
}
  1. 创建PetMapperAnnotation.java
public interface PetMapperAnnotation {//通过User的id来获取pet对象,可能有多个,因此使用List接收/*** 1、通过User的id来获取pet对象,可能有多个,因此使用List接收* 2、public List<Pet> getPetByUserId(Integer userId);* 3. 完成的思路和前面大体相同.* <resultMap id="PetResultMap" type="Pet">* <id property="id" column="id"/>* <result property="nickname" column="nickname"/>* <association property="user" column="user_id"* select="com.nlc.mapper.UserMapper.getUserById" />* </resultMap>* <select id="getPetByUserId" parameterType="Integer" resultMap="PetResultMap">* SELECT * FROM `mybatis_pet` WHERE `user_id` = #{userId}* </select>*///id = "PetResultMap" 就是给我们的Results[Result Map] 指定一个名字//目的是为了后面复用@Select("SELECT * FROM `mybatis_pet` WHERE `user_id` = #{userId}")@Results(id = "PetResultMap", value = {@Result(id = true, property = "id", column = "id"),@Result(property = "nickname", column = "nickname"),@Result(property = "user",column = "user_id",one = @One(select = "com.nlc.mapper.UserMapperAnnotation.getUserById"))})public List<Pet> getPetByUserId(Integer userId);//通过pet的id获取Pet对象, 同时会查询到pet对象关联的user对象/*** <select id="getPetById"  parameterType="Integer"  resultMap="PetResultMap">* SELECT * FROM `mybatis_pet` WHERE `id` = #{id}* </select>* @ResultMap("PetResultMap") 使用/引用我们上面定义的 Results[ResultMap]*/@Select("SELECT * FROM `mybatis_pet` WHERE `id` = #{id}")@ResultMap("PetResultMap")public Pet getPetById(Integer id);
}
  1. 创建UserMapperAnnotationTest.java 完成测试
public class UserMapperAnnotationTest {//属性private SqlSession sqlSession;private UserMapperAnnotation userMapperAnnotation;//初始化@Beforepublic void init() {//获取到sqlSessionsqlSession = MyBatisUtils.getSqlSession();userMapperAnnotation = sqlSession.getMapper(UserMapperAnnotation.class);}@Testpublic void getUserById() {User user = userMapperAnnotation.getUserById(2);System.out.println("user信息-" + user.getId() + "-" + user.getName());List<Pet> pets = user.getPets();for (Pet pet : pets) {System.out.println("宠物信息-" + pet.getId() + "-" + pet.getNickname());}if(sqlSession != null) {sqlSession.close();}}
}
  1. 创建PetMapperAnnotationTest.java 完成测试
public class PetMapperAnnotationTest {//属性private SqlSession sqlSession;private PetMapperAnnotation petMapperAnnotation;//初始化@Beforepublic void init() {//获取到sqlSessionsqlSession = MyBatisUtils.getSqlSession();petMapperAnnotation = sqlSession.getMapper(PetMapperAnnotation.class);}@Testpublic void getPetByUserId() {List<Pet> pets = petMapperAnnotation.getPetByUserId(1);for (Pet pet : pets) {System.out.println("宠物信息-" + pet.getId() + "-" + pet.getNickname());}if(sqlSession != null) {sqlSession.close();}}@Testpublic void getPetById() {Pet pet = petMapperAnnotation.getPetById(1);System.out.println("pet信息-" + pet.getId() + "-" +pet.getNickname());User user = pet.getUser();System.out.println("user信息-" + user.getId() + "-" + user.getName());if(sqlSession != null) {sqlSession.close();}}
}

相关文章:

快速了解MyBatis---映射关系多对一

文章目录 映射关系多对一映射关系-官方文档映射关系多对1-基本介绍基本介绍注意细节 映射关系多对1-映射方式映射方式配置Mapper.xml 方式-应用实例注解实现多对1 映射-应用实例 映射关系多对一 映射关系-官方文档 文档地址: https://mybatis.org/mybatis-3/zh/sqlmap-xml.ht…...

python学到什么程度算入门,python从入门到精通好吗

本篇文章给大家谈谈python学到什么程度算入门&#xff0c;以及python从入门到精通好吗&#xff0c;希望对各位有所帮助&#xff0c;不要忘了收藏本站喔。 学习 Python 之 进阶学习 一切皆对象 1. 变量和函数皆对象2. 模块和类皆对象3. 对象的基本操作 (1). 可以赋值给变量(2). …...

整数规划——第一章 引言

整数规划——第一章 引言 整数规划是带整数变量的最优化问题&#xff0c;即最大化或最小化一个全部或部分变量为整数的多元函数受约束于一组等式和不等式条件的最优化问题。许多经济、管理、交通、通信和工程中的最优化问题都可以用整数规划来建模。 考虑一个电视机工厂的生产…...

C语言结构体讲解

目录 结构体的声明 结构的基础知识 结构的声明 为什么要出现结构体&#xff1f; 结构成员的类型 结构体变量的定义和初始化 定义&#xff1a;&#xff08;全局变量//局部变量&#xff09; 初始化&#xff1a; 结构体成员的访问 结构体传参 结构体的声明 结构的基础知识…...

021 - STM32学习笔记 - Fatfs文件系统(三) - 细化与总结

021 - STM32学习笔记 - Fatfs文件系统&#xff08;三&#xff09; - 细化与总结 上节内容中&#xff0c;初步实现了FatFs文件系统的移植&#xff0c;并且实现了设备的挂载、文件打开/关闭与读写功能&#xff0c;这里对上节遗留的一些问题进行总结&#xff0c;并且继续完善文件…...

jQuery如何获取动态添加的元素

jQuery如何获取动态添加的元素 使用 on()方法 本质上使用了事件委派&#xff0c;将事件委派在父元素身上 自 jQuery 版本 1.7 起&#xff0c;on() 方法是 bind()、live() 和 delegate() 方法的新的替代品&#xff0c;但是由于on()方法必须有事件&#xff0c;没有事件时可选择de…...

Keepalived 在CentOS 7安装并配置监听MySQL双主

keepalived安装 MySQL双主配置请看这里&#xff1a;https://tongyao.blog.csdn.net/article/details/132016200?spm1001.2014.3001.5502 128、129两台服务器安装步骤相同&#xff0c;配置文件不同&#xff0c;下面有介绍。 1.安装相关依赖包&#xff0c;并下载keepalived安…...

深度学习,神经网络介绍

目录 1.神经网络的整体构架 2.神经网络架构细节 3.正则化与激活函数 4.神经网络过拟合解决方法 1.神经网络的整体构架 ConvNetJS demo: Classify toy 2D data 我们可以看看这个神经网络的网站&#xff0c;可以用来学习。 神经网络的整体构架如下1&#xff1a; 感知器&…...

中国AI大模型峰会“封神之作”!开发者不容错过这场夏季盛会

年度最强大模型顶会来袭&#xff01;喊话中国数百万AI开发者&#xff0c;速来&#xff01; 硬核来袭&#xff01;中国AI大模型峰会“封神之作”&#xff0c;开发者们不容错过! 前瞻大模型发展趋势&#xff0c;紧跟这场大会&#xff01; 中国科技超级碗&#xff0c;大模型最新前…...

Android Studio多渠道打包

使用环境&#xff1a; Android studio 多渠道打包 使用方法&#xff1a; 1 APP下build.gradle文件 flavorDimensions "default"productFlavors {huawei {dimension "default"manifestPlaceholders [ channel:"huawei" ]}xiaomi {dimension &…...

RK3566 Android11默认客户Launcher修改

前言 客户需要默认自己的Launcher为home,同时保留系统的Launcher3. 解决办法:在启动home应用之前设置一下默认Launcher。查找home app启动相关资料,找到了frameworks/base/services/core/java/com/android/server/wm/RootWindowContainer.java的startHomeOnTaskDisplayA…...

ORB算法在opencv中实现方法

在OPenCV中实现ORB算法&#xff0c;使用的是&#xff1a; 1.实例化ORB orb cv.xfeatures2d.orb_create(nfeatures)参数&#xff1a; nfeatures: 特征点的最大数量 2.利用orb.detectAndCompute()检测关键点并计算 kp,des orb.detectAndCompute(gray,None)参数&#xff1a…...

vue项目回显文本无法识别换行符

解决方法 1&#xff1a;使用<br/>替换文本中的\n&#xff0c;使用v-html渲染 <template> <div v-html"str"></div> </template> <script> let str 以下内容自动换行\n换行了 // 使用replace截取提换 this.str str.replace(/…...

Minio 部署

minio 官网&#xff1a;https://www.minio.org.cn/ 部署文档&#xff1a;https://www.minio.org.cn/docs/minio/container/operations/install-deploy-manage/deploy-minio-single-node-single-drive.html# 选择自己的部署环境&#xff1a; 我用的docker: docker pull qua…...

Kafka系列之:记录一次Kafka Topic分区扩容,但是下游flink消费者没有自动消费新的分区的解决方法

Kafka系列之:记录一次Kafka Topic分区扩容,但是下游flink消费者没有自动消费新的分区的解决方法 一、背景二、解决方法三、实现自动发现新的分区一、背景 生产环境Kafka集群压力大,Topic读写压力大,消费的lag比较大,因此通过扩容Topic的分区,增大Topic的读写性能理论上下…...

Ansible部署MariaDB galera集群(多主)

文章目录 Ansible部署MariaDB galera集群(多主)介绍节点规划基础环境准备编写剧本文件执行剧本文件查看集群状态测试 Ansible部署MariaDB galera集群(多主) 介绍 MariaDB Galera集群是一套基于同步复制的、多主的MySQL集群解决方案&#xff0c;使用节点没有单点故障&#xff…...

立体库-库龄

split 用法第一种&#xff1a; 1.对单个字符进行分割&#xff08;注意这里是字符&#xff0c;不是字符串&#xff0c;故只能用单引号‘’&#xff09; string sabcdeabcdeabcde; string[] sArrays.Split(c) ; foreach(string i in sArray) Console.WriteLine(i.ToString());…...

extern/头文件包含,实现一个函数被两个文件共用

目录 一、extern 1、在a.c文件中定义int add函数 2、在b.c文件中使用extern关键字声明add函数 二、用头文件包含的形式 1、在a.c文件中定义int add函数 2、创建一个名为a.h的头文件&#xff0c;其中包含add函数的函数原型 3、在b.c文件中包含a.c的头文件&#xff0c;并调…...

pgsql 查看某个表建立了那些索引sql

执行以下sql&#xff1a; SELECTns.nspname as schema_name,tab.relname as table_name,cls.relname as index_name,am.amname as index_type,idx.indisprimary as is_primary,idx.indisunique as is_unique FROMpg_index idx INNER JOIN pg_class cls ON cls.oididx.indexrel…...

【SCSS】网格布局中的动画

效果 index.html <!DOCTYPE html> <html><head><title> Document </title><link type"text/css" rel"styleSheet" href"index.css" /></head><body><div class"container">&l…...

label-studio的使用教程(导入本地路径)

文章目录 1. 准备环境2. 脚本启动2.1 Windows2.2 Linux 3. 安装label-studio机器学习后端3.1 pip安装(推荐)3.2 GitHub仓库安装 4. 后端配置4.1 yolo环境4.2 引入后端模型4.3 修改脚本4.4 启动后端 5. 标注工程5.1 创建工程5.2 配置图片路径5.3 配置工程类型标签5.4 配置模型5.…...

React Native 导航系统实战(React Navigation)

导航系统实战&#xff08;React Navigation&#xff09; React Navigation 是 React Native 应用中最常用的导航库之一&#xff0c;它提供了多种导航模式&#xff0c;如堆栈导航&#xff08;Stack Navigator&#xff09;、标签导航&#xff08;Tab Navigator&#xff09;和抽屉…...

蓝牙 BLE 扫描面试题大全(2):进阶面试题与实战演练

前文覆盖了 BLE 扫描的基础概念与经典问题蓝牙 BLE 扫描面试题大全(1)&#xff1a;从基础到实战的深度解析-CSDN博客&#xff0c;但实际面试中&#xff0c;企业更关注候选人对复杂场景的应对能力&#xff08;如多设备并发扫描、低功耗与高发现率的平衡&#xff09;和前沿技术的…...

自然语言处理——循环神经网络

自然语言处理——循环神经网络 循环神经网络应用到基于机器学习的自然语言处理任务序列到类别同步的序列到序列模式异步的序列到序列模式 参数学习和长程依赖问题基于门控的循环神经网络门控循环单元&#xff08;GRU&#xff09;长短期记忆神经网络&#xff08;LSTM&#xff09…...

大学生职业发展与就业创业指导教学评价

这里是引用 作为软工2203/2204班的学生&#xff0c;我们非常感谢您在《大学生职业发展与就业创业指导》课程中的悉心教导。这门课程对我们即将面临实习和就业的工科学生来说至关重要&#xff0c;而您认真负责的教学态度&#xff0c;让课程的每一部分都充满了实用价值。 尤其让我…...

力扣-35.搜索插入位置

题目描述 给定一个排序数组和一个目标值&#xff0c;在数组中找到目标值&#xff0c;并返回其索引。如果目标值不存在于数组中&#xff0c;返回它将会被按顺序插入的位置。 请必须使用时间复杂度为 O(log n) 的算法。 class Solution {public int searchInsert(int[] nums, …...

C/C++ 中附加包含目录、附加库目录与附加依赖项详解

在 C/C 编程的编译和链接过程中&#xff0c;附加包含目录、附加库目录和附加依赖项是三个至关重要的设置&#xff0c;它们相互配合&#xff0c;确保程序能够正确引用外部资源并顺利构建。虽然在学习过程中&#xff0c;这些概念容易让人混淆&#xff0c;但深入理解它们的作用和联…...

【Linux】自动化构建-Make/Makefile

前言 上文我们讲到了Linux中的编译器gcc/g 【Linux】编译器gcc/g及其库的详细介绍-CSDN博客 本来我们将一个对于编译来说很重要的工具&#xff1a;make/makfile 1.背景 在一个工程中源文件不计其数&#xff0c;其按类型、功能、模块分别放在若干个目录中&#xff0c;mak…...

aardio 自动识别验证码输入

技术尝试 上周在发学习日志时有网友提议“在网页上识别验证码”&#xff0c;于是尝试整合图像识别与网页自动化技术&#xff0c;完成了这套模拟登录流程。核心思路是&#xff1a;截图验证码→OCR识别→自动填充表单→提交并验证结果。 代码在这里 import soImage; import we…...

【实施指南】Android客户端HTTPS双向认证实施指南

&#x1f510; 一、所需准备材料 证书文件&#xff08;6类核心文件&#xff09; 类型 格式 作用 Android端要求 CA根证书 .crt/.pem 验证服务器/客户端证书合法性 需预置到Android信任库 服务器证书 .crt 服务器身份证明 客户端需持有以验证服务器 客户端证书 .crt 客户端身份…...