MyBatis见解3

8.MyBatis的关联查询

8.3.一对多查询

需求:查询所有用户信息及用户关联的账户信息。

分析:用户信息和他的账户信息为一对多关系,并且查询过程中如果用户没有账户信息,此时也要将用户信息查询出来,此时左外连接查询比较合适。

8.3.1.pojo

package com.by.pojo;import java.io.Serializable;
import java.util.Date;
import java.util.List;public class User implements Serializable {private Integer id;private String username;private Date birthday;private String sex;private String address;private List<Account> account;@Overridepublic String toString() {return "User{" +"id=" + id +", username='" + username + '\'' +", birthday=" + birthday +", sex='" + sex + '\'' +", address='" + address + '\'' +", account=" + account +'}';}public List<Account> getAccount() {return account;}public void setAccount(List<Account> account) {this.account = account;}public Integer getId() {return id;}public void setId(Integer id) {this.id = id;}public String getUsername() {return username;}public void setUsername(String username) {this.username = username;}public Date getBirthday() {return birthday;}public void setBirthday(Date birthday) {this.birthday = birthday;}public String getSex() {return sex;}public void setSex(String sex) {this.sex = sex;}public String getAddress() {return address;}public void setAddress(String address) {this.address = address;}}

8.3.2.mapper

package com.by.dao;import com.by.pojo.User;import java.util.List;public interface UserDao {User getUserById(Integer id);
}
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapperPUBLIC "-//mybatis.org//DTD Mapper 3.0//EN""http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<resultMap id="getUserByIdResultMap" type="user"><id column="id" property="id"></id><result column="username" property="username"></result><result column="birthday" property="birthday"></result><result column="sex" property="sex"></result><result column="address" property="address"></result><!--一对多使用collection标签指定数据的封装规则--><collection property="account" ofType="account"><id column="aid" property="id"></id><result column="uid" property="uid"></result><result column="money" property="money"></result></collection></resultMap><select id="getUserById" parameterType="int" resultMap="getUserByIdResultMap">SELECTu.*,a.id aid,a.money money,a.uid uidFROMuser uLEFT JOINaccount aONu.id=a.uidWHEREu.id=#{id}</select>

8.3.3.测试

    /*** 一对多:一个user 对 多个Account*/@Testpublic void testGetUsertById() throws IOException {UserDao userDao = sqlSession.getMapper(UserDao.class);User user = userDao.getUserById(41);System.out.println(user);}

8.4.多对多查询

需求:查询角色及角色赋予的用户信息。

分析:一个用户可以拥有多个角色,一个角色也可以赋予多个用户,用户和角色为双向的一对多关系,多对多关系其实我们看成是双向的一对多关系。
在这里插入图片描述
user(uid, username):王贺、万通

​ user_role(uid, rid)

role(rid, ):校长、老师、学生

8.3.1.pojo

package com.by.pojo;import java.util.List;
// 一方
public class Role {private Integer id;private String roleName;private String roleDesc;// 多方private List<User> user;@Overridepublic String toString() {return "Role{" +"id=" + id +", roleName='" + roleName + '\'' +", roleDesc='" + roleDesc + '\'' +", user=" + user +'}';}public Integer getId() {return id;}public void setId(Integer id) {this.id = id;}public String getRoleName() {return roleName;}public void setRoleName(String roleName) {this.roleName = roleName;}public String getRoleDesc() {return roleDesc;}public void setRoleDesc(String roleDesc) {this.roleDesc = roleDesc;}public List<User> getUser() {return user;}public void setUser(List<User> user) {this.user = user;}
}

8.3.2.mapper

package com.by.dao;import com.by.pojo.Role;public interface RoleMapper {Role getRoleById(Integer id);
}
<?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="com.by.dao.RoleMapper"><resultMap id="getRoleByIdResultMap" type="role"><id column="rid" property="id"></id><result column="role_name" property="roleName"></result><result column="role_desc" property="roleDesc"></result><!--一对多使用collection标签指定数据的封装规则property="userList":pojo的属性ofType="com.by.pojo.User":集合的泛型,等价于resultType--><collection property="user" ofType="user"><id column="id" property="id"></id><result column="username" property="username"></result><result column="birthday" property="birthday"></result><result column="sex" property="sex"></result><result column="address" property="address"></result></collection></resultMap><select id="getRoleById" parameterType="int" resultMap="getRoleByIdResultMap">SELECTr.id rid,role_name,role_desc,u.*FROMuser_role urLEFT JOINrole rONur.rid=r.idLEFT JOINuser uONur.uid=u.idWHEREr.id=#{id}</select>
</mapper>

8.3.3.测试

   /*** 多对多:一个user 对 多个role   一个role 对 多个user*/@Testpublic void testGetRoletById() throws IOException {RoleMapper roleMapper = sqlSession.getMapper(RoleMapper.class);Role role = roleMapper.getRoleById(1);System.out.println(role);}

9.MyBatis的延迟加载

创建工程:
在这里插入图片描述

9.1.什么是延迟加载?

开启延迟加载后,在真正使用数据的时候才发起级联查询,不用的时候不查询。

9.2.mapper

package com.by.dao;import com.by.pojo.User;import java.util.List;public interface UserDao {User getUserById2(Integer id);
}
<?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="com.by.dao.UserDao"><!--id:和接口方法名保持一致resultType:和接口返回类型保持一致--><select id="findAll" resultType="com.by.pojo.User">select * from user</select><select id="getUserById" parameterType="int" resultType="user">select * from user where id=#{id}</select><resultMap id="getUserById2ResultMap" type="user"><id column="id" property="id"></id><result column="username" property="username"></result><result column="birthday" property="birthday"></result><result column="sex" property="sex"></result><result column="address" property="address"></result><!--property="accountList":pojo的属性ofType="account":集合的泛型select="com.by.mapper.AccountMapper.selectAccountByUid":要调用的select标签的idcolumn="id":传递的参数fetchType="lazy":局部开启延迟加载--><collection property="accountList" ofType="account" select="com.by.dao.AccountMapper.selectAccountById" column="id" fetchType="lazy"></collection></resultMap><select id="getUserById2" parameterType="int" resultMap="getUserById2ResultMap">SELECT * FROM user WHERE id=#{id}</select>
</mapper>

9.3.全局开启懒加载

    <!-- 全局配置延迟加载策略 --><settings><!--  打开延迟加载的开关  --><setting name="lazyLoadingEnabled" value="true"/></settings>

9.4.测试

    @Testpublic void testGetUserById2() throws IOException {UserDao userDao = sqlSession.getMapper(UserDao.class);User user = userDao.getUserById2(41);System.out.println(user.getUsername());List<Account> accountList = user.getAccountList();for (Account account : accountList) {System.out.println(account);}}

10.MyBatis的动态SQL

创建工程:
在这里插入图片描述

10.1.什么是动态SQL?

MyBatis的映射文件中支持在基础SQL上添加一些逻辑操作,并动态拼接成完整的SQL之后再执行,以达到SQL复用、简化编程的效果。

10.2.if标签

我们根据实体类的不同取值,使用不同的SQL语句来进行查询。比如在id如果不为空时可以根据 id查询,如果username不同空时还要加入用户名作为条件。这种情况在我们的多条件组合查询中经常会碰到。
mapper接口

package com.by.dao;import com.by.pojo.User;import java.util.List;public interface UserDao {User findAll2(User user);
}

mapper映射文件

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapperPUBLIC "-//mybatis.org//DTD Mapper 3.0//EN""http://mybatis.org/dtd/mybatis-3-mapper.dtd"><select id="findAll2" parameterType="user" resultType="user">SELECT * FROM user<where><if test="id != null">AND id=#{id}</if><if test="sex != null and sex != ''">AND sex=#{sex}</if></where></select>

测试

    public void testFindAll2(){UserDao userDao = sqlSession.getMapper(UserDao.class);User user = new User();user.setId(41);user.setSex("男");System.out.println(userDao.findAll2(user));}

10.3.where标签

为了简化上面where 1=1的条件拼装,我们可以使用where标签将if标签代码块包起来,将1=1条件去掉。

若查询条件的开头为 “AND” 或 “OR”,where 标签会将它们去除。
mapper映射文件

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapperPUBLIC "-//mybatis.org//DTD Mapper 3.0//EN""http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<!--namespace:隔离sql,一般是接口名称的全类名-->
<mapper namespace="com.by.dao.UserDao">
<select id="findByUser" resultType="User">select * from user<!--where标签将if标签代码块包起来去掉开头 “AND” 或 “OR--><where><if test="username!=null and username != ''">and username=#{username}</if><if test="birthday!=null">and birthday=#{birthday}</if><if test="sex!=null and sex != ''">and sex=#{sex}</if><if test="address!=null and address != ''">and address=#{address}</if></where></select></mapper>

10.4.set标签

set标签用于动态包含需要更新的列,并会删掉额外的逗号
mapper

package com.by.dao;import com.by.pojo.User;import java.util.List;public interface UserDao {void updateUserById(User user);
}
    <update id="updateUserById" parameterType="user">UPDATE user<set><if test="username != null and username != ''">username=#{username},</if></set>WHERE id=#{id}</update>

测试

    @Testpublic void testUpdateUserById(){UserDao userDao = sqlSession.getMapper(UserDao.class);User user = new User();user.setId(41);user.setUsername("杨过");userDao.updateUserById(user);}

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

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

相关文章

Android Matrix画布Canvas缩放scale,Kotlin

Android Matrix画布Canvas缩放scale&#xff0c;Kotlin val originBmp BitmapFactory.decodeResource(resources, R.mipmap.pic).copy(Bitmap.Config.ARGB_8888, true)val newBmp Bitmap.createBitmap(originBmp.width, originBmp.height, Bitmap.Config.ARGB_8888)val canva…

P1883 函数

题目链接 P1883 函数 思路 举例 题目中的 F ( x ) F(x) F(x) 看起来很复杂&#xff0c;但由于每个 f ( x ) f(x) f(x) 的二次项系数 a a a 都不是负数&#xff0c;故 F ( x ) F(x) F(x) 是一个单谷函数。直接说出结论可能有些令人难以接受&#xff0c;不妨举出两个例子…

视频姿态估计:DeciWatch

DeciWatch: A Simple Baseline for 10 Efficient 2D and 3D Pose Estimation解析 摘要1. 简介2. Related Work2.1 高效的人体姿态估计2.2 Motion Completion(运动补全)3. Method3.1 问题定义和概述3.2 获取采样姿势3.3 Denoising the Sampled Poses(去噪采样的姿态)3.4 Rec…

Ubuntu环境下使用Livox mid 360

参考文章&#xff1a; Ubuntu 20.04使用Livox mid 360 测试 FAST_LIO-CSDN博客 一&#xff1a;Livox mid 360驱动安装与测试 前言&#xff1a; Livox mid360需要使用Livox-SDK2&#xff0c;而非Livox-SDK&#xff0c;以及对应的livox_ros_driver2 。并需要修改FAST_LIO中部…

FastAPI实现文件上传下载

FastAPI实现文件上传下载 1.后端FastAPI2.后端html3.效果 最近的项目需求&#xff0c;是前端vue&#xff0c;后端fastAPI&#xff0c;然后涉及到图像的消息发送&#xff0c;所以需要用fast写文件上传下载的接口&#xff0c;这里简单记录一下。 1.后端FastAPI import os.path i…

P1308 [NOIP2011 普及组] 统计单词数

P1308 [NOIP2011 普及组] 统计单词数 P1308 [NOIP2011 普及组] 统计单词数 P1308 [NOIP2011 普及组] 统计单词数 题意 一行&#xff0c;如果在文章中找到给定单词则输出两个整数&#xff0c;两个整数之间用一个空格隔开&#xff0c;分别是单词在文章中出现的次数和第一次出现…

【安全】audit的一些问题以及需要注意的地方

audit的一些问题以及需要注意的地方 1 audit存在的一些问题 1.1 audit_cmd_mutex锁占用的问题 当内核生成审计日志后&#xff0c;会以单播形式发送给用户态的某个进程&#xff0c;因此&#xff0c;某个程序如果想要接受审计日志&#xff0c;需要先调用audit_set_pid&#xf…

.net core webapi 大文件上传到wwwroot文件夹

1.配置staticfiles(program文件中) app.UseStaticFiles();2.在wwwroot下创建upload文件夹 3.返回结果封装 namespace webapi;/// <summary> /// 统一数据响应格式 /// </summary> public class Results<T> {/// <summary>/// 自定义的响应码&#xff…

H266/VVC帧内预测编码

预测编码技术 预测编码&#xff08;Prediction Coding&#xff09;是指利用已编码的一个或多个样本值&#xff0c;根据某种模型或方法&#xff0c;对当前的样本值进行预测&#xff0c;并对样本真实值和预测值之间的差值进行编码。 视频中的每个像素看成一个信源符号&#xff…

python3 数据分析项目案例,用python做数据分析案例

本篇文章给大家谈谈python3 数据分析项目案例&#xff0c;以及用python做数据分析案例&#xff0c;希望对各位有所帮助&#xff0c;不要忘了收藏本站喔。 目录 一丶可视化绘图案例 1.曲线图 2.柱形图 3.点线图 4.3D散点图 5. 绘制漏斗图 6. 绘制词云图 二丶包/模块使用示例 (1)…

高通切换到Emergency Download:adb reboot edl

刷机 开机下adb reboot edl 切到QDloader 9008 点下载。 The command “adb reboot edl” is used to reboot an Android device into EDL (Emergency Download) mode using the Android Debug Bridge (ADB) tool. EDL mode is primarily used for low-level firmware flashing…

数据结构---算法的空间复杂度

文章目录 空间复杂度概念实例 空间复杂度 概念 空间复杂度也是一个数学表达式&#xff0c;是对一个算法在运行过程中临时占用存储空间大小的量度 。 空间复杂度不是程序占用了多少bytes的空间&#xff0c;因为这个也没太大意义&#xff0c;所以空间复杂度算的是变量的个数。…

NLP中的嵌入层

在自然语言处理&#xff08;NLP&#xff09;中&#xff0c;嵌入层&#xff08;Embedding Layer&#xff09;是一个特殊的层&#xff0c;通常用于深度学习模型的第一层&#xff0c;它的作用是将离散的文本数据&#xff08;如单词或短语&#xff09;转换为连续的向量表示。每个单…

LLM之RAG实战(八)| 使用Neo4j和LlamaIndex实现多模态RAG

人工智能和大型语言模型领域正在迅速发展。一年前&#xff0c;没有人使用LLM来提高生产力。时至今日&#xff0c;很难想象我们大多数人或多或少都在使用LLM提供服务&#xff0c;从个人助手到文生图场景。由于大量的研究和兴趣&#xff0c;LLM每天都在变得越来越好、越来越聪明。…

[node]Node.js 模块系统

[node]模块系统 Node.js中的模块系统模块的使用模块的导入模块的导出导出多个值导出默认值导出可传参的函数 文件查找策略从文件模块缓存中加载从原生模块加载从文件加载 Node.js中的模块系统 为了让Node.js的文件可以相互调用&#xff0c;Node.js提供了一个简单的模块系统。 …

【第七在线】数据分析与人工智能在商品计划中的应用

随着技术的不断进步&#xff0c;数据分析和人工智能&#xff08;AI&#xff09;已经成为了现代商品计划的关键组成部分。在服装行业&#xff0c;这两项技术正在帮助企业更好地理解市场需求、优化库存管理、提高生产效率和提供更好的客户体验。本文将深入探讨数据分析和人工智能…

机器学习笔记(二)使用paddlepaddle,再探波士顿房价预测

目标 用paddlepaddle来重写之前那个手写的梯度下降方案&#xff0c;简化内容 流程 实际上就做了几个事&#xff1a; 数据准备&#xff1a;将一个批次的数据先转换成nparray格式&#xff0c;再转换成Tensor格式前向计算&#xff1a;将一个批次的样本数据灌入网络中&#xff…

华为---登录USG6000V防火墙---console、web、telnet、ssh方式登录

目录 一、环境搭建 二、第一次登录USG6000V防火墙&#xff0c;即通过console方式登录 三、用户配置 四、web登录USG6000V防火墙 1. 用web创建的用户通过web方式登录USG6000V防火墙 2. 命令行创建的用户通过web方式登录USG6000V防火墙 五、ssh方式登录USG6000V防火墙 1. 用…

从CTF中学习自增构造webshell

FLAG&#xff1a;那天晚上和你聊了很久&#xff0c;手机烫的和心脏一样 专研方向: 代码审计&#xff0c;Crypto 每日emo&#xff1a;天一亮&#xff0c;时间就不属于我了 从CTF中学习自增构造webshell 前言1.异或2.自增3.取反青少年CTF之ezbypass 前言 今天写了几道代码审计的…

Android MVI架构之UI状态的持有与保存

Android MVI架构之UI状态的持有与保存 我们将介绍状态持有者和其他与 UI 层相关的主题&#xff0c;例如在 Android 上提升状态和保存 UI 状态的位置。 状态持有者 状态持有者通过处理逻辑和/或公开 UI 状态来简化 UI。在本节中&#xff0c;我们将看到如何实现状态持有者以及…