Mybatis入门——语法详解:基础使用、增删改查、起别名、解决问题、注释、动态查询,从入门到进阶
文章目录
- 1.基础使用
- 1.添加依赖
- 2.在resouces文件下新建xml文件db.properties
- 3.在resouces文件下新建xml文件mybatis-config-xml
- 4.创建一个MybatisUtils工具类
- 5.创建xml文件XxxMapper.xml映射dao层接口
- 6.添加日志
- 5.测试
- 2.增删改查
- 1.select
- 2.delete
- 3.update
- 4.insert
- 5.模糊查询
- 6.分页查询
- 3.起别名
- 3.1具体的某个文件
- 3.2给包名起别名
- 3.3用注解起别名
- 4.解决实体属性名与数据库列名不一致问题
- 1.建一个resultMap标签
- 2.引用
- 5.使用注解
- 5.1在接口上写注解
- 5.2进行绑定
- 6.association和collection
- 6.1一对多
- 6.2多对一
- 7.动态查询
- 7.1模糊查询if标签
- 7.2更新数据set标签
- 7.3Forech
- 8.二级缓存
- 8.1在mybatis-config.xml中开启全局缓存
- 8.1添加局部缓存,在xxMapper.xml中添加
1.基础使用
1.添加依赖
<dependency><groupId>mysql</groupId><artifactId>mysql-connector-java</artifactId><version>8.0.18</version></dependency><dependency><groupId>junit</groupId><artifactId>junit</artifactId><version>4.12</version></dependency><!-- https://mvnrepository.com/artifact/org.mybatis/mybatis --><dependency><groupId>org.mybatis</groupId><artifactId>mybatis</artifactId><version>3.4.6</version></dependency>
<build>
<resources><resource><directory>src/main/resources</directory><includes><include>**/*.properties</include><include>**/*.xml</include></includes><filtering>false</filtering></resource><resource><directory>src/main/java</directory><includes><include>**/*.properties</include><include>**/*.xml</include></includes><filtering>false</filtering></resource>
</resources>
</build>
2.在resouces文件下新建xml文件db.properties
写配置文件
driver=com.mysql.cj.jdbc.Driver
url=jdbc:mysql://localhost:3306/mybatis?serverTimezone=Asia/Shanghai&useSSL=true&useUnicode=true&characterEncoding=utf-8
username=root
password=DRsXT5ZJ6Oi55LPQ
3.在resouces文件下新建xml文件mybatis-config-xml
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configurationPUBLIC "-//mybatis.org//DTD Config 3.0//EN""http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration><properties resource="db.properties"/><environments default="development"><environment id="development"><transactionManager type="JDBC"/><dataSource type="POOLED"><property name="driver" value="${driver}"/><property name="url" value="${url}"/><property name="username" value="${username}"/><property name="password" value="${password}"/></dataSource></environment></environments><mappers><mapper resource="com/tuzhi/dao/UserMapper.xml"/></mappers>
</configuration>
4.创建一个MybatisUtils工具类
public class MybatisUtils {private static SqlSessionFactory sqlSessionFactory;static {String resource = "org/mybatis/example/mybatis-config.xml";InputStream inputStream = null;try {inputStream = Resources.getResourceAsStream(resource);} catch (IOException e) {e.printStackTrace();}sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);}public SqlSession getSqlSession() {return sqlSessionFactory.openSession();}
}
5.创建xml文件XxxMapper.xml映射dao层接口
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapperPUBLIC "-//mybatis.org//DTD Mapper 3.0//EN""http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<!--映射dao层接口-->
<mapper namespace="com.tuzhi.dao.UserDao">
<!-- 映射接口里面的方法--><select id="getUserList" resultType="com.tuzhi.pojo.User">select * from user</select>
</mapper>
6.添加日志
<settings><setting name="logImpl" value="LOG4J"/><!-- 是否开启驼峰命名自动映射,即从经典数据库列名 A_COLUMN 映射到经典 Java 属性名 aColumn。--><setting name="mapUnderscoreToCamelCase" value="true"/><!-- 开启全局缓存--><setting name="cacheEnabled" value="true"/></settings>
5.测试
@Testpublic void test() {SqlSession sqlSession = MybatisUtils.getSqlSession();UserDao userDao = sqlSession.getMapper(UserDao.class);List<User> userList = userDao.getUserList();for (User user : userList) {System.out.println(user);}sqlSession.close();}
2.增删改查
1.select
<select id="getUserById" resultType="com.tuzhi.pojo.User" parameterType="int">select * from user where id = #{id}</select>
2.delete
<delete id="deleteUser" parameterType="com.tuzhi.pojo.User">deletefrom USERwhere id = #{id};</delete>
3.update
<update id="updateUser" parameterType="com.tuzhi.pojo.User">update USERset name = #{name},pwd = #{pwd}where id = #{id};</update>
4.insert
<insert id="addUser" parameterType="com.tuzhi.pojo.User">insert into USER (id,name ,pwd)values (#{id},#{name},#{pwd});</insert>
5.模糊查询
<select id="getUserListLike" resultType="com.tuzhi.pojo.User">select * from user where name like concat('%',#{name},'%')</select>
6.分页查询
<!-- 分页查询--><select id="getUserLimit" parameterType="map" resultMap="userResultMap">select * from user limit #{startIndex},#{pageSize}</select>
3.起别名
3.1具体的某个文件
<typeAliases><typeAlias alias="Author" type="domain.blog.Author"/><typeAlias alias="Blog" type="domain.blog.Blog"/><typeAlias alias="Comment" type="domain.blog.Comment"/><typeAlias alias="Post" type="domain.blog.Post"/><typeAlias alias="Section" type="domain.blog.Section"/><typeAlias alias="Tag" type="domain.blog.Tag"/>
</typeAliases>
3.2给包名起别名
<typeAliases><package name="domain.blog"/>
</typeAliases>
注,用别名的时候直接用文件名,全小写
3.3用注解起别名
@Alias("author")
注,直接在类上注解
4.解决实体属性名与数据库列名不一致问题
1.建一个resultMap标签
<resultMap id="userResultMap" type="User">//property实体类里的,column数据库里的<id property="id" column="user_id" /><result property="username" column="user_name"/><result property="password" column="hashed_password"/>
</resultMap>
2.引用
然后在引用它的语句中设置 resultMap 属性就行了(注意我们去掉了 resultType 属性)。比如:
<select id="selectUsers" resultMap="userResultMap">select user_id, user_name, hashed_passwordfrom some_tablewhere id = #{id}
</select>
5.使用注解
5.1在接口上写注解
public interface UserMapper {// 使用注解@Select("select * from user")List<User> getUserListAnnotate();
}
5.2进行绑定
<mappers><mapper class="com.tuzhi.dao.UserMapper"/>
</mappers>
6.association和collection
association用于对象,关联
collection用于集合
6.1一对多
-
实体类
@Data @AllArgsConstructor @NoArgsConstructor public class Student {private int id;private String name;private Teacher teacher; }@Data @AllArgsConstructor @NoArgsConstructor public class Teacher {private int id;private String name; } -
第一种查询
<!-- 第一种多对一查询--> <select id="getUserList1" resultMap="studentTeacher1">select * from student </select> <resultMap id="studentTeacher1" type="Student"><association property="teacher" column="tid" select="getTeacherListById"/> </resultMap> <select id="getTeacherListById" resultType="Teacher">select * from teacher where id = #{tid} </select> -
第二种查询
<!-- 第二种多对一查询--> <select id="getUserList2" resultMap="studentTeacher2">select s.id sid,s.name sname,t.id tid,t.name tnamefrom student s,teacher twhere s.tid = t.id </select> <resultMap id="studentTeacher2" type="Student"><result property="id" column="sid"/><result property="name" column="sname"/><association property="teacher" javaType="Teacher"><result property="id" column="tid"/><result property="name" column="tname"/></association> </resultMap>
6.2多对一
-
实体类
@Data @AllArgsConstructor @NoArgsConstructor public class Student {private int id;private String name; }@Data @AllArgsConstructor @NoArgsConstructor public class Teacher {private int id;private String name;private List<Student> student; } -
第一种查询
<!-- 第一种查询--><select id="getTeacherListById1" resultMap="teacherStudent1">select t.id id,t.name tname,s.id sid,s.name sname,s.tid tidfrom teacher t,student swhere t.id=s.tid</select><resultMap id="teacherStudent1" type="Teacher"><result property="id" column="id"/><result property="name" column="tname"/><collection property="student" ofType="Student"><result property="id" column="sid"/><result property="name" column="sname"/></collection></resultMap> -
第二种查询
<!-- 第二种查询--><select id="getTeacherListById2" resultMap="teacherStudent2">select * from teacher where id = #{id}</select><resultMap id="teacherStudent2" type="Teacher"><collection property="student" javaType="Arraylist" ofType="Student" column="id" select="getStudentList"/></resultMap><select id="getStudentList" resultType="Student">select * from student where tid = #{id}</select>
7.动态查询
7.1模糊查询if标签
- 接口
//查询
List<Blog> getBlogIf(Map map);
- if
<!-- 动态sql模糊查询-->
<select id="getBlogIf" parameterType="map" resultType="blog">select * from blog<where><if test="title != null">and title like concat('%',#{title},'%')</if><if test="author != null">and author like concat('%',#{author}.'%')</if></where></select>
7.2更新数据set标签
-
接口
-
set标签
<!-- 动态更新数据--> <update id="updateBlog" parameterType="Blog">update blog<set><if test="title != null">title = #{title},</if><if test="author != null">author = #{author},</if><if test="views != null">views = #{views},</if></set>where id = #{id} </update>
7.3Forech
-
forech
<select id="queryForeach" parameterType="map" resultType="Blog">select * from blog<where><foreach collection="ids" item="id" open="and (" separator="or" close=")">id = #{id}</foreach></where> </select> -
测试
@Test public void queryForech() {SqlSession sqlSession = MybatisUtils.getSqlSession();BlogMapper mapper = sqlSession.getMapper(BlogMapper.class);ArrayList arrayList = new ArrayList();arrayList.add(1);arrayList.add(2);HashMap hashMap = new HashMap();hashMap.put("ids",arrayList);mapper.queryForeach(hashMap);sqlSession.close(); }
8.二级缓存
8.1在mybatis-config.xml中开启全局缓存
<setting name="cacheEnabled" value="true"/>
8.1添加局部缓存,在xxMapper.xml中添加
<cacheeviction="FIFO"flushInterval="60000"size="512"readOnly="true"/>
相关文章:
Mybatis入门——语法详解:基础使用、增删改查、起别名、解决问题、注释、动态查询,从入门到进阶
文章目录 1.基础使用1.添加依赖2.在resouces文件下新建xml文件db.properties3.在resouces文件下新建xml文件mybatis-config-xml4.创建一个MybatisUtils工具类5.创建xml文件XxxMapper.xml映射dao层接口6.添加日志5.测试 2.增删改查1.select2.delete3.update4.insert5.模糊查询6.…...
仓库选址问题【数学规划的应用(含代码)】阿里达院MindOpt
本文主要讲述使用MindOpt工具优化仓库选址的数学规划问题。 视频讲解👈👈👈👈👈👈👈👈👈 一、案例场景 仓库选址问题在现代物流和供应链管理中具有重要的应用。因为仓库…...
Docker Compose 一键快速部署 RocketMQ
Apache RocketMQ是一个开源的分布式消息中间件系统,最初由阿里巴巴开发并贡献给Apache软件基金会。RocketMQ提供了高性能、高可靠性、高扩展性和低延迟的消息传递服务,适用于构建大规模分布式系统中的消息通信和数据同步。 RocketMQ支持多种消息模型&am…...
Vscode lanuch.json
Intro 使用launch.json 能够方便的运行需要传很多参数的代码文件 如下: import math import argparse # 1、导入argpase包def parse_args():parse argparse.ArgumentParser(descriptionCalculate cylinder volume) # 2、创建参数对象parse.add_argument(--rad…...
Golang开发:构建支持并发的网络爬虫
Golang开发:构建支持并发的网络爬虫 随着互联网的快速发展,获取网络数据成为了许多应用场景中的关键需求。网络爬虫作为一种自动化获取网络数据的工具,也因此迅速崛起。而为了应对日益庞大的网络数据,开发支持并发的爬虫成为了必…...
2024年跨境电商关键数据统计:市场规模将达到1.976万亿美元
预计2024年跨境电商消费市场规模将达到1.976万亿美元,占全球网上销售总额的31.2%。这一数据无疑展示了跨境电商市场的巨大潜力和迅猛增长趋势。 全球跨境电商的现状与未来 现状 2023年,全球跨境电商市场规模预计达到1.56万亿美元,占全球电子…...
联想至像M3070DNA打印机加粉及清零方法
基本参数: 产品类型:黑白激光多功能商用一体机(打印/复印/扫描) 网络功能:支持有线网络打印 最大处理幅面:A4 双面功能:自动 打印速度:30页/分钟(高速激光打印&…...
通过nginx去除 api url前缀 并保持后面剩余的url不变向后台请求
如 我前台浏览器向后台请求的接口是 http://127.0.0.1:5099/api/sample/sample/getbuttonlist 实际的请求接口传向 http://192.168.3.71:5099/sample/sample/getbuttonlist 方法是向config中加入下面这样一个server server {listen 5099;location /api/ {rewrite ^/a…...
AI技术在现代社会中的广泛应用及其影响
目录 前言: 一、AI技术在医疗领域的应用 二、AI技术在教育领域的应用 三、AI技术在工业领域的应用 四、AI技术在金融领域的应用 五、AI技术在生活领域的应用 前言: 随着科技的不断发展,人工智能(AI)技术逐渐成为人…...
VBA 批量变换文件名
1. 页面布局 在“main”Sheet中按照下面的格式编辑。 2. 实现代码 Private wsMain As Worksheet Private intIdx As LongPrivate Sub getExcelBookList(strPath As String)Dim fso As ObjectDim objFile As ObjectDim objFolder As ObjectSet fso = CreateObject("Scrip…...
OpenHarmony 5.0 纯血鸿蒙系统
OpenHarmony-v5.0-Beta1 版本已于 2024-06-20 发布。 OpenHarmony 5.0 Beta1 版本标准系统能力持续完善,ArkUI 完善了组件通过 C API 调用的能力;应用框架细化了生命周期管理能力,完善了应用拉起、跳转的能力;分布式软总线连接能力…...
计算机网络地址划分A-E(自学)
1、网络地址组成 (1)物理地址MAC(Media Access Control Address) 网卡生产商分配,全球唯一,48/64位二进制 (2)逻辑地址IP(Internet Protocol) 网络层地址,用于在不同网…...
js导入导出
好久没有学习新的知识点了,今天开始学一下前端的知识点。直接在vscode里面编写,然后从基本的前端知识开始。 JS的导入导出 <!DOCTYPE html> <html lang"en"><head><meta charset"UTF-8"><meta name"…...
python办公自动化之excel
用到的库:openpyxl 实现效果:读取单元格的值,写入单元格 代码: import openpyxl # 打开现有工作簿 workbookopenpyxl.load_workbook(现有工作簿.xlsx) # 选择一个工作表 sheetworkbook[交易表] # 读取单元格的值 cell_valueshe…...
生命在于学习——Python人工智能原理(2.5.1)
五、Python的类与继承 5.1 Python面向对象编程 在现实世界中存在各种不同形态的事物,这些事物之间存在各种各样的联系。在程序中使用对象来映射现实中的事物,使用对象之间的关系描述事物之间的联系,这种思想用在编程中就是面向对象编程。 …...
visual studio 2022配置和使用jsoncpp
下载 jsoncpp下载位置: GitHub - open-source-parsers/jsoncpp: A C library for interacting with JSON. 编译库 1、下载完成之后解压 2、在解压文件的makefiles文件下有个vs71,在vs71中有visual studio项目,不过这里的项目是visual stud…...
Spring Boot中的动态数据源切换
Spring Boot中的动态数据源切换 大家好,我是免费搭建查券返利机器人省钱赚佣金就用微赚淘客系统3.0的小编,也是冬天不穿秋裤,天冷也要风度的程序猿!今天,我们将探讨如何在Spring Boot中实现动态数据源切换的技术。动态…...
npm error code EUNSUPPORTEDPROTOCOL 解决
更换包管理工具 npm i -g pnpm pnpm install pnpm run dev 参考 https://blog.csdn.net/qq_42592823/article/details/137541827...
基于改进天鹰优化算法(IAO)优化支持向量机(SVM)数据分类预测(IAO-SVM)
改进天鹰优化算法(IAO)见:【智能优化算法】改进的AO算法(IAO)-CSDN博客 支持向量机(SVM)数据分类预测:基于支持向量机(SVM)的数据分类预测-CSDN博客 代码原理 基于改进天鹰优化算法(IAO)优化支持向量机(SVM…...
【数学建模】—【Python库】—【Numpy】—【学习】
目录 编辑 1. NumPy安装 2. ndarray对象 1. 创建ndarray 1.从列表或元组创建: 2.使用内置函数创建: 2. ndarray属性 3. 数组运算 1. 基本运算 2. 数学函数 3.统计函数 4. 数组索引与切片 1. 一维数组索引与切片 2.多维数组索引与切片 5.…...
AtCoder 第409场初级竞赛 A~E题解
A Conflict 【题目链接】 原题链接:A - Conflict 【考点】 枚举 【题目大意】 找到是否有两人都想要的物品。 【解析】 遍历两端字符串,只有在同时为 o 时输出 Yes 并结束程序,否则输出 No。 【难度】 GESP三级 【代码参考】 #i…...
抖音增长新引擎:品融电商,一站式全案代运营领跑者
抖音增长新引擎:品融电商,一站式全案代运营领跑者 在抖音这个日活超7亿的流量汪洋中,品牌如何破浪前行?自建团队成本高、效果难控;碎片化运营又难成合力——这正是许多企业面临的增长困局。品融电商以「抖音全案代运营…...
转转集团旗下首家二手多品类循环仓店“超级转转”开业
6月9日,国内领先的循环经济企业转转集团旗下首家二手多品类循环仓店“超级转转”正式开业。 转转集团创始人兼CEO黄炜、转转循环时尚发起人朱珠、转转集团COO兼红布林CEO胡伟琨、王府井集团副总裁祝捷等出席了开业剪彩仪式。 据「TMT星球」了解,“超级…...
linux arm系统烧录
1、打开瑞芯微程序 2、按住linux arm 的 recover按键 插入电源 3、当瑞芯微检测到有设备 4、松开recover按键 5、选择升级固件 6、点击固件选择本地刷机的linux arm 镜像 7、点击升级 (忘了有没有这步了 估计有) 刷机程序 和 镜像 就不提供了。要刷的时…...
vue3 字体颜色设置的多种方式
在Vue 3中设置字体颜色可以通过多种方式实现,这取决于你是想在组件内部直接设置,还是在CSS/SCSS/LESS等样式文件中定义。以下是几种常见的方法: 1. 内联样式 你可以直接在模板中使用style绑定来设置字体颜色。 <template><div :s…...
视频字幕质量评估的大规模细粒度基准
大家读完觉得有帮助记得关注和点赞!!! 摘要 视频字幕在文本到视频生成任务中起着至关重要的作用,因为它们的质量直接影响所生成视频的语义连贯性和视觉保真度。尽管大型视觉-语言模型(VLMs)在字幕生成方面…...
土地利用/土地覆盖遥感解译与基于CLUE模型未来变化情景预测;从基础到高级,涵盖ArcGIS数据处理、ENVI遥感解译与CLUE模型情景模拟等
🔍 土地利用/土地覆盖数据是生态、环境和气象等诸多领域模型的关键输入参数。通过遥感影像解译技术,可以精准获取历史或当前任何一个区域的土地利用/土地覆盖情况。这些数据不仅能够用于评估区域生态环境的变化趋势,还能有效评价重大生态工程…...
MySQL中【正则表达式】用法
MySQL 中正则表达式通过 REGEXP 或 RLIKE 操作符实现(两者等价),用于在 WHERE 子句中进行复杂的字符串模式匹配。以下是核心用法和示例: 一、基础语法 SELECT column_name FROM table_name WHERE column_name REGEXP pattern; …...
【学习笔记】深入理解Java虚拟机学习笔记——第4章 虚拟机性能监控,故障处理工具
第2章 虚拟机性能监控,故障处理工具 4.1 概述 略 4.2 基础故障处理工具 4.2.1 jps:虚拟机进程状况工具 命令:jps [options] [hostid] 功能:本地虚拟机进程显示进程ID(与ps相同),可同时显示主类&#x…...
重启Eureka集群中的节点,对已经注册的服务有什么影响
先看答案,如果正确地操作,重启Eureka集群中的节点,对已经注册的服务影响非常小,甚至可以做到无感知。 但如果操作不当,可能会引发短暂的服务发现问题。 下面我们从Eureka的核心工作原理来详细分析这个问题。 Eureka的…...
