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

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工具优化仓库选址的数学规划问题。 视频讲解&#x1f448;&#x1f448;&#x1f448;&#x1f448;&#x1f448;&#x1f448;&#x1f448;&#x1f448;&#x1f448; 一、案例场景 仓库选址问题在现代物流和供应链管理中具有重要的应用。因为仓库…...

Docker Compose 一键快速部署 RocketMQ

Apache RocketMQ是一个开源的分布式消息中间件系统&#xff0c;最初由阿里巴巴开发并贡献给Apache软件基金会。RocketMQ提供了高性能、高可靠性、高扩展性和低延迟的消息传递服务&#xff0c;适用于构建大规模分布式系统中的消息通信和数据同步。 RocketMQ支持多种消息模型&am…...

Vscode lanuch.json

Intro 使用launch.json 能够方便的运行需要传很多参数的代码文件 如下&#xff1a; import math import argparse # 1、导入argpase包def parse_args():parse argparse.ArgumentParser(descriptionCalculate cylinder volume) # 2、创建参数对象parse.add_argument(--rad…...

Golang开发:构建支持并发的网络爬虫

Golang开发&#xff1a;构建支持并发的网络爬虫 随着互联网的快速发展&#xff0c;获取网络数据成为了许多应用场景中的关键需求。网络爬虫作为一种自动化获取网络数据的工具&#xff0c;也因此迅速崛起。而为了应对日益庞大的网络数据&#xff0c;开发支持并发的爬虫成为了必…...

2024年跨境电商关键数据统计:市场规模将达到1.976万亿美元

预计2024年跨境电商消费市场规模将达到1.976万亿美元&#xff0c;占全球网上销售总额的31.2%。这一数据无疑展示了跨境电商市场的巨大潜力和迅猛增长趋势。 全球跨境电商的现状与未来 现状 2023年&#xff0c;全球跨境电商市场规模预计达到1.56万亿美元&#xff0c;占全球电子…...

联想至像M3070DNA打印机加粉及清零方法

基本参数&#xff1a; 产品类型&#xff1a;黑白激光多功能商用一体机&#xff08;打印/复印/扫描&#xff09; 网络功能&#xff1a;支持有线网络打印 最大处理幅面&#xff1a;A4 双面功能&#xff1a;自动 打印速度&#xff1a;30页/分钟&#xff08;高速激光打印&…...

通过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技术在现代社会中的广泛应用及其影响

目录 前言&#xff1a; 一、AI技术在医疗领域的应用 二、AI技术在教育领域的应用 三、AI技术在工业领域的应用 四、AI技术在金融领域的应用 五、AI技术在生活领域的应用 前言&#xff1a; 随着科技的不断发展&#xff0c;人工智能&#xff08;AI&#xff09;技术逐渐成为人…...

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 版本标准系统能力持续完善&#xff0c;ArkUI 完善了组件通过 C API 调用的能力&#xff1b;应用框架细化了生命周期管理能力&#xff0c;完善了应用拉起、跳转的能力&#xff1b;分布式软总线连接能力…...

计算机网络地址划分A-E(自学)

1、网络地址组成 &#xff08;1&#xff09;物理地址MAC&#xff08;Media Access Control Address&#xff09; 网卡生产商分配&#xff0c;全球唯一&#xff0c;48/64位二进制 &#xff08;2&#xff09;逻辑地址IP(Internet Protocol) 网络层地址&#xff0c;用于在不同网…...

js导入导出

好久没有学习新的知识点了&#xff0c;今天开始学一下前端的知识点。直接在vscode里面编写&#xff0c;然后从基本的前端知识开始。 JS的导入导出 <!DOCTYPE html> <html lang"en"><head><meta charset"UTF-8"><meta name"…...

python办公自动化之excel

用到的库&#xff1a;openpyxl 实现效果&#xff1a;读取单元格的值&#xff0c;写入单元格 代码&#xff1a; import openpyxl # 打开现有工作簿 workbookopenpyxl.load_workbook(现有工作簿.xlsx) # 选择一个工作表 sheetworkbook[交易表] # 读取单元格的值 cell_valueshe…...

生命在于学习——Python人工智能原理(2.5.1)

五、Python的类与继承 5.1 Python面向对象编程 在现实世界中存在各种不同形态的事物&#xff0c;这些事物之间存在各种各样的联系。在程序中使用对象来映射现实中的事物&#xff0c;使用对象之间的关系描述事物之间的联系&#xff0c;这种思想用在编程中就是面向对象编程。 …...

visual studio 2022配置和使用jsoncpp

下载 jsoncpp下载位置&#xff1a; GitHub - open-source-parsers/jsoncpp: A C library for interacting with JSON. 编译库 1、下载完成之后解压 2、在解压文件的makefiles文件下有个vs71&#xff0c;在vs71中有visual studio项目&#xff0c;不过这里的项目是visual stud…...

Spring Boot中的动态数据源切换

Spring Boot中的动态数据源切换 大家好&#xff0c;我是免费搭建查券返利机器人省钱赚佣金就用微赚淘客系统3.0的小编&#xff0c;也是冬天不穿秋裤&#xff0c;天冷也要风度的程序猿&#xff01;今天&#xff0c;我们将探讨如何在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)见&#xff1a;【智能优化算法】改进的AO算法(IAO)-CSDN博客 支持向量机(SVM)数据分类预测&#xff1a;基于支持向量机(SVM)的数据分类预测-CSDN博客 代码原理 基于改进天鹰优化算法&#xff08;IAO&#xff09;优化支持向量机&#xff08;SVM&#xf…...

【数学建模】—【Python库】—【Numpy】—【学习】

目录 ​编辑 1. NumPy安装 2. ndarray对象 1. 创建ndarray 1.从列表或元组创建&#xff1a; 2.使用内置函数创建&#xff1a; 2. ndarray属性 3. 数组运算 1. 基本运算 2. 数学函数 3.统计函数 4. 数组索引与切片 1. 一维数组索引与切片 2.多维数组索引与切片 5.…...

谷歌浏览器插件

项目中有时候会用到插件 sync-cookie-extension1.0.0&#xff1a;开发环境同步测试 cookie 至 localhost&#xff0c;便于本地请求服务携带 cookie 参考地址&#xff1a;https://juejin.cn/post/7139354571712757767 里面有源码下载下来&#xff0c;加在到扩展即可使用FeHelp…...

vscode里如何用git

打开vs终端执行如下&#xff1a; 1 初始化 Git 仓库&#xff08;如果尚未初始化&#xff09; git init 2 添加文件到 Git 仓库 git add . 3 使用 git commit 命令来提交你的更改。确保在提交时加上一个有用的消息。 git commit -m "备注信息" 4 …...

日语学习-日语知识点小记-构建基础-JLPT-N4阶段(33):にする

日语学习-日语知识点小记-构建基础-JLPT-N4阶段(33):にする 1、前言(1)情况说明(2)工程师的信仰2、知识点(1) にする1,接续:名词+にする2,接续:疑问词+にする3,(A)は(B)にする。(2)復習:(1)复习句子(2)ために & ように(3)そう(4)にする3、…...

JavaScript 中的 ES|QL:利用 Apache Arrow 工具

作者&#xff1a;来自 Elastic Jeffrey Rengifo 学习如何将 ES|QL 与 JavaScript 的 Apache Arrow 客户端工具一起使用。 想获得 Elastic 认证吗&#xff1f;了解下一期 Elasticsearch Engineer 培训的时间吧&#xff01; Elasticsearch 拥有众多新功能&#xff0c;助你为自己…...

基于uniapp+WebSocket实现聊天对话、消息监听、消息推送、聊天室等功能,多端兼容

基于 ​UniApp + WebSocket​实现多端兼容的实时通讯系统,涵盖WebSocket连接建立、消息收发机制、多端兼容性配置、消息实时监听等功能,适配​微信小程序、H5、Android、iOS等终端 目录 技术选型分析WebSocket协议优势UniApp跨平台特性WebSocket 基础实现连接管理消息收发连接…...

Qt Http Server模块功能及架构

Qt Http Server 是 Qt 6.0 中引入的一个新模块&#xff0c;它提供了一个轻量级的 HTTP 服务器实现&#xff0c;主要用于构建基于 HTTP 的应用程序和服务。 功能介绍&#xff1a; 主要功能 HTTP服务器功能&#xff1a; 支持 HTTP/1.1 协议 简单的请求/响应处理模型 支持 GET…...

数据链路层的主要功能是什么

数据链路层&#xff08;OSI模型第2层&#xff09;的核心功能是在相邻网络节点&#xff08;如交换机、主机&#xff09;间提供可靠的数据帧传输服务&#xff0c;主要职责包括&#xff1a; &#x1f511; 核心功能详解&#xff1a; 帧封装与解封装 封装&#xff1a; 将网络层下发…...

今日学习:Spring线程池|并发修改异常|链路丢失|登录续期|VIP过期策略|数值类缓存

文章目录 优雅版线程池ThreadPoolTaskExecutor和ThreadPoolTaskExecutor的装饰器并发修改异常并发修改异常简介实现机制设计原因及意义 使用线程池造成的链路丢失问题线程池导致的链路丢失问题发生原因 常见解决方法更好的解决方法设计精妙之处 登录续期登录续期常见实现方式特…...

return this;返回的是谁

一个审批系统的示例来演示责任链模式的实现。假设公司需要处理不同金额的采购申请&#xff0c;不同级别的经理有不同的审批权限&#xff1a; // 抽象处理者&#xff1a;审批者 abstract class Approver {protected Approver successor; // 下一个处理者// 设置下一个处理者pub…...

JS手写代码篇----使用Promise封装AJAX请求

15、使用Promise封装AJAX请求 promise就有reject和resolve了&#xff0c;就不必写成功和失败的回调函数了 const BASEURL ./手写ajax/test.jsonfunction promiseAjax() {return new Promise((resolve, reject) > {const xhr new XMLHttpRequest();xhr.open("get&quo…...