当前位置: 首页 > 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.…...

使用docker在3台服务器上搭建基于redis 6.x的一主两从三台均是哨兵模式

一、环境及版本说明 如果服务器已经安装了docker,则忽略此步骤,如果没有安装,则可以按照一下方式安装: 1. 在线安装(有互联网环境): 请看我这篇文章 传送阵>> 点我查看 2. 离线安装(内网环境):请看我这篇文章 传送阵>> 点我查看 说明&#xff1a;假设每台服务器已…...

Vue记事本应用实现教程

文章目录 1. 项目介绍2. 开发环境准备3. 设计应用界面4. 创建Vue实例和数据模型5. 实现记事本功能5.1 添加新记事项5.2 删除记事项5.3 清空所有记事 6. 添加样式7. 功能扩展&#xff1a;显示创建时间8. 功能扩展&#xff1a;记事项搜索9. 完整代码10. Vue知识点解析10.1 数据绑…...

Lombok 的 @Data 注解失效,未生成 getter/setter 方法引发的HTTP 406 错误

HTTP 状态码 406 (Not Acceptable) 和 500 (Internal Server Error) 是两类完全不同的错误&#xff0c;它们的含义、原因和解决方法都有显著区别。以下是详细对比&#xff1a; 1. HTTP 406 (Not Acceptable) 含义&#xff1a; 客户端请求的内容类型与服务器支持的内容类型不匹…...

c++ 面试题(1)-----深度优先搜索(DFS)实现

操作系统&#xff1a;ubuntu22.04 IDE:Visual Studio Code 编程语言&#xff1a;C11 题目描述 地上有一个 m 行 n 列的方格&#xff0c;从坐标 [0,0] 起始。一个机器人可以从某一格移动到上下左右四个格子&#xff0c;但不能进入行坐标和列坐标的数位之和大于 k 的格子。 例…...

UR 协作机器人「三剑客」:精密轻量担当(UR7e)、全能协作主力(UR12e)、重型任务专家(UR15)

UR协作机器人正以其卓越性能在现代制造业自动化中扮演重要角色。UR7e、UR12e和UR15通过创新技术和精准设计满足了不同行业的多样化需求。其中&#xff0c;UR15以其速度、精度及人工智能准备能力成为自动化领域的重要突破。UR7e和UR12e则在负载规格和市场定位上不断优化&#xf…...

QT: `long long` 类型转换为 `QString` 2025.6.5

在 Qt 中&#xff0c;将 long long 类型转换为 QString 可以通过以下两种常用方法实现&#xff1a; 方法 1&#xff1a;使用 QString::number() 直接调用 QString 的静态方法 number()&#xff0c;将数值转换为字符串&#xff1a; long long value 1234567890123456789LL; …...

第 86 场周赛:矩阵中的幻方、钥匙和房间、将数组拆分成斐波那契序列、猜猜这个单词

Q1、[中等] 矩阵中的幻方 1、题目描述 3 x 3 的幻方是一个填充有 从 1 到 9 的不同数字的 3 x 3 矩阵&#xff0c;其中每行&#xff0c;每列以及两条对角线上的各数之和都相等。 给定一个由整数组成的row x col 的 grid&#xff0c;其中有多少个 3 3 的 “幻方” 子矩阵&am…...

视觉slam十四讲实践部分记录——ch2、ch3

ch2 一、使用g++编译.cpp为可执行文件并运行(P30) g++ helloSLAM.cpp ./a.out运行 二、使用cmake编译 mkdir build cd build cmake .. makeCMakeCache.txt 文件仍然指向旧的目录。这表明在源代码目录中可能还存在旧的 CMakeCache.txt 文件,或者在构建过程中仍然引用了旧的路…...

【JVM面试篇】高频八股汇总——类加载和类加载器

目录 1. 讲一下类加载过程&#xff1f; 2. Java创建对象的过程&#xff1f; 3. 对象的生命周期&#xff1f; 4. 类加载器有哪些&#xff1f; 5. 双亲委派模型的作用&#xff08;好处&#xff09;&#xff1f; 6. 讲一下类的加载和双亲委派原则&#xff1f; 7. 双亲委派模…...

Vue 实例的数据对象详解

Vue 实例的数据对象详解 在 Vue 中,数据对象是响应式系统的核心,也是组件状态的载体。理解数据对象的原理和使用方式是成为 Vue 专家的关键一步。我将从多个维度深入剖析 Vue 实例的数据对象。 一、数据对象的定义方式 1. Options API 中的定义 在 Options API 中,使用 …...