MyBatis-常用SQL操作

news2025/7/19 2:47:12

一、动态SQL

1.概述】

1.1动态SQL: 是 MyBatis 的强大特性之一,解决拼接动态SQL时候的难题,提高开发效

1.2分类:

  • if

  • choose(when,otherwise)

  • trim(where,set)

  • foreach

2.if

2.1 做 where 语句后面条件查询的,if 语句是可以拼接多条的。

2.2 需求:根据学生name 做模糊查询

代码:

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
        PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
        "https://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="cn.wjcoder.mapper.StudentMapper">


    <select id="selectLikeName" resultType="cn.wjcoder.domain.Student">
        select id,name,age
        from student
        where age = 20
        <if test="name != null">
            and name like concat(#{name},'%')
        </if>
    </select>
</mapper>
public interface StudentMapper {

    List<Student> selectLikeName(String name);
}

3.choose、when、otherwise

3.1概述:

不想使用所有条件时候,他们可以从多个条件中选择一个使用,相当于java 的 if ... else if ... else。

3.2需求:按年龄20查找,如果id 不空按id 查找,名字不空按名字查找,否则按班级id 查找

<select id="selectChoose" resultType="cn.wjcoder.domain.Student">
        select <include refid="baseSql"/>
        from student
        where age = 20
        <choose>
            <when test="id != null">
                and id = #{id}
            </when>
            <when test="name != null">
                and name like concat(#{name},'%')
            </when>
            <otherwise>
                and class_id = #{clsTd}
            </otherwise>
        </choose>
    </select>
 List<Student> selectChoose(@Param("id") Long id,
@Param("name") String name,@Param("clsId") Long clsId);

3.3不传 id 参数,传入name = 'z'  

3.4不传入 id 参数和 name 参数

4.trim、where、set

4.1trim

  • trim : 用于去掉或者添加标签中的内容
  • prefix:可以在 trim 标签内容前面添加内容

  • prefixOverrides:可以覆盖前面的某些内容  

  • suffix:在 trim 标签后面添加内容  

  • suffixOverrides:去掉 trim 标签内容最后面的值  

4.2where

  • where 后面直接跟 if  

  • age null  

  •  使用了 where 标签之后,解决了这些问题

4.3set

  • set 元素可以用于动态包含需要更新的列

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
        PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
        "https://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="cn.wjcoder.mapper.StudentMapper">

    <sql id="baseSql">
        id,name,age
    </sql>
    <update id="updateSet">
        update student
        <set>
            <if test="name != null">
                name =#{name},
            </if>
            <if test="age != null">
                age = #{age},
            </if>
        </set>
        <where>
            <if test="id != null">
                id = #{id}
            </if>
        </where>
    </update>
void updateSet(@Param("age") Integer age,@Param("name")String name
            ,@Param("clsId") Long clsId,@Param("id")Long id);

5.foreach

  • foreach :用于对集合遍历。 动态 SQL 的另一个常见使用场景是对集合进行遍历(尤其是在构建 IN 条件语句的时候)

<select id="selectForeach" resultType="cn.wjcoder.domain.Student">
        select * from student
        <where>
            <foreach collection="ids" item="id" index="i" open="id in(" close=")" separator=",">
                    #{id}
            </foreach>
        </where>
    </select>
List<Student> selectForeach(@Param("ids") List<Long> ids);

  • collection:传参的数组集合

  • item:遍历拿到的每一个元素

  • index:索引

  • open : foreach 标签内容的开始符

  • close : foreach 标签内容的结束符

  • separator:分隔符

  • 取值取的就是 item 的元素值

  • 注意:当使用 Map 对象(或者 Map.Entry 对象的集合)时,index 是键,item 是值。

6.script

  • script:要在带注解的映射器接口类中使用动态 SQL,可以使用 script 元素。

  • 使用注解操作 mybatis

需求:查询所有的学生信息,用注解方式实现

@Select("select * from student")
    List<Student> selectAll();

更新学生信息,使用 script 标签

@Update({
            "<script>",
            "update student",
            "  <set>",
            "    <if test='name != null'>name=#{name},</if>",
            "    <if test='age != null'>age=#{age},</if>",
            "    <if test='clsId != null'>class_id=#{clsId},</if>",
            "  </set>",
            "where id=#{id}",
            "</script>"
    })
    void updateStu(@Param("age") Integer age,@Param("name")String name
            ,@Param("clsId") Long clsId,@Param("id")Long id);

7.bind

  • bind 元素允许你在 OGNL 表达式以外创建一个变量,并将其绑定到当前的上下文。

  • 需求:通过用户name 进行模糊查询

<select id="listLike" resultType="cn.sycoder.domain.Student">
        <bind name="ret" value="'%' + name + '%'"/>
        select * from student
        where name like #{ret}
    </select>

二、MyBatis api

1.概述

*官方的不用

  • 用下面这种 

2.SqlSession

2.1概述:

通过这个接口SqlSession来执行命令,获取映射器实例和管理事务,SqlSessions 是由 SqlSessionFactory 实例创建的。SqlSessionFactory 对象包含创建 SqlSession 实例的各种方法。而 SqlSessionFactory 本身是由 SqlSessionFactoryBuilder 创建的,它可以从 XML、注解或 Java 配置代码来创建 SqlSessionFactory。

2.2SqlSessionFactoryBuilder

  • 有 5 个 builder 方法
SqlSessionFactory build(InputStream inputStream)
SqlSessionFactory build(InputStream inputStream, String environment)
SqlSessionFactory build(InputStream inputStream, Properties properties)
SqlSessionFactory build(InputStream inputStream, String env, Properties props)
SqlSessionFactory build(Configuration config)

2.3SqlSessionFactory

  • 获取方式
String resource = "mybatis-config.xml";
InputStream inputStream = Resources.getResourceAsStream(resource);
SqlSessionFactoryBuilder builder = new SqlSessionFactoryBuilder();
SqlSessionFactory factory = builder.build(inputStream);

  • 最终会将xml 配置文件,或者 properties 配置转换成一个 Configuration ,最后一个 build 方法接受一个 Configuration 实例。Configuration 类包含了对一个 SqlSessionFactory 实例你可能关心的所有内容。

  • Configuration 类信息

  • 提供了六个方法创建 SqlSession 的实例
SqlSession openSession()
SqlSession openSession(boolean autoCommit)
SqlSession openSession(Connection connection)
SqlSession openSession(TransactionIsolationLevel level)
SqlSession openSession(ExecutorType execType, TransactionIsolationLevel level)
SqlSession openSession(ExecutorType execType)
SqlSession openSession(ExecutorType execType, boolean autoCommit)
SqlSession openSession(ExecutorType execType, Connection connection)
Configuration getConfiguration();
  •  主要支持如下操作
    • 事务处理:你希望在 session 作用域中使用事务作用域,还是使用自动提交(auto-commit)?(对很多数据库和/或 JDBC 驱动来说,等同于关闭事务支持)

    • 数据库连接:你希望 MyBatis 帮你从已配置的数据源获取连接,还是使用自己提供的连接?

    • 语句执行:你希望 MyBatis 复用 PreparedStatement 和/或批量更新语句(包括插入语句和删除语句)吗?

  • 默认的 openSession() 方法没有参数,它会创建具备如下特性的 SqlSession:

    • 事务作用域将会开启(也就是不自动提交

    • 将由当前环境配置的 DataSource 实例中获取 Connection 对象。(mybatis-config.xml)

    • 事务隔离级别将会使用驱动或数据源的默认设置(mysql 默认REPEATABLE_READ)

    • 预处理语句不会被复用,也不会批量处理更新。

  • 如果你需要开启事务自动提交

    • autoCommit 可选参数传递 true 值即可开启自动提交功能

  • 如果你需要提供数据库隔离级别

    • 修改这个的值TransactionIsolationLevel ,提供了枚举

如果你需要修改执行类型

  • 修改ExecutorType值

    • ExecutorType.SIMPLE:该类型的执行器没有特别的行为。它为每个语句的执行创建一个新的预处理语句。

    • ExecutorType.REUSE:该类型的执行器会复用预处理语句。

    • ExecutorType.BATCH:该类型的执行器会批量执行所有更新语句,如果 SELECT 在多个更新中间执行,将在必要时将多条更新语句分隔开来,以方便理解。

2.4SqlSession

  • 语句执行方法:这些方法被用来执行定义在 SQL 映射 XML 文件中的 SELECT、INSERT、UPDATE 和 DELETE 语句。

    <T> T selectOne(String statement, Object parameter)
    <E> List<E> selectList(String statement, Object parameter)
    <T> Cursor<T> selectCursor(String statement, Object parameter)
    <K,V> Map<K,V> selectMap(String statement, Object parameter, String mapKey)
    int insert(String statement, Object parameter)
    int update(String statement, Object parameter)
    int delete(String statement, Object parameter)
  • RowBounds(可用于分页需求)

    int offset = 100;
    int limit = 25;
    RowBounds rowBounds = new RowBounds(offset, limit);
  • 立即批量更新方法(如果不调用这个方法,批处理不执行,只是缓存而已)

    List<BatchResult> flushStatements()
  • 事务控制方法

    void commit()
    void commit(boolean force)
    void rollback()
    void rollback(boolean force)
  • 本地缓存:Mybatis 使用到了两种缓存:

    • 本地缓存(local cache):每当一个新 session 被创建,MyBatis 就会创建一个与之相关联的本地缓存

    • 二级缓存(second level cache)

    • 清空本地缓存(一般不去动)

      void clearCache()
    • 确保 SqlSession 被关闭:如果没有使用新特性的方式,一定要finally手动关闭

      void close()

2.5使用映射器

  • 方法
<T> T getMapper(Class<T> type)
  • 自定义方法执行最终都是调用 mybatis 的方法实现
public interface AuthorMapper {
  // (Author) selectOne("selectAuthor",5);
  Author selectAuthor(int id);
  // (List<Author>) selectList(“selectAuthors”)
  List<Author> selectAuthors();
  // (Map<Integer,Author>) selectMap("selectAuthors", "id")
  @MapKey("id")
  Map<Integer, Author> selectAuthors();
  // insert("insertAuthor", author)
  int insertAuthor(Author author);
  // updateAuthor("updateAuthor", author)
  int updateAuthor(Author author);
  // delete("deleteAuthor",5)
  int deleteAuthor(int id);
}
  • 映射器注解

  • 映射注解示例

插入语句

@Insert("insert into table3 (id, name) values(#{nameId}, #{name})")
int insertTable3(Name name);

 查询语句

@Results(id = "userResult", value = {
  @Result(property = "id", column = "uid", id = true),
  @Result(property = "firstName", column = "first_name"),
  @Result(property = "lastName", column = "last_name")
})
@Select("select * from users where id = #{id}")
User getUserById(Integer id);

三、分页查询

1.概述

MyBatis 分页插件 PageHelper:是一款非常不错,并且企业用得很多的mybatis 分页插件

2.如何使用

2.1引入分页插件

导入 maven 依赖 pom

<dependency>
    <groupId>com.github.pagehelper</groupId>
    <artifactId>pagehelper</artifactId>
    <version>5.3.0</version>
</dependency>

2.2配置拦截插件

  • 在 spring 中配置

<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
  <!-- 注意其他配置 -->
  <property name="plugins">
    <array>
      <bean class="com.github.pagehelper.PageInterceptor">
        <property name="properties">
          <!--使用下面的方式配置参数,一行配置一个 -->
          <value>
            params=value1
          </value>
        </property>
      </bean>
    </array>
  </property>
</bean>
  • 在 MyBatis 配置 xml 中配置拦截器插件
<!--
    plugins在配置文件中的位置必须符合要求,否则会报错,顺序如下:
    properties?, settings?,
    typeAliases?, typeHandlers?,
    objectFactory?,objectWrapperFactory?,
    plugins?,
    environments?, databaseIdProvider?, mappers?
-->
<plugins>
    <!-- com.github.pagehelper为PageHelper类所在包名 -->
    <plugin interceptor="com.github.pagehelper.PageInterceptor">
        <!-- 使用下面的方式配置参数,后面会有所有的参数介绍 -->
        <property name="param1" value="value1"/>
	</plugin>
</plugins>

2.3分页插件参数介绍

pageNum : 当前页码,pageSize : 每页显示的数量,list : 分页后的集合数据,total : 总记录数,

pages : 总页数,prePage : 上一页,nextPage: 下一页。

2.4具体使用

  • 开启分页拦截查询
//①:开启分页功能,参数1是当前页码,参数是每页显示的条数
PageHelper.startPage(1, 2);
  • 执行查询
//②:开始执行结果,返回list
List<Student> list = mapper.selectAll();
Page page = (Page) list;
PageInfo<Student> info = new PageInfo<>(list);
System.out.println(list);

page 里面包含的属性

private int pageNum;
private int pageSize;
private long total;
private int pages;

四、实战SQL常用操作

1.插入时获取主键

1.1注解方式

1.2xml 配置的方式

<insert id="insertXml" useGeneratedKeys="true" keyProperty="id" keyColumn="id">
    insert into student values(null,#{name},#{age},#{classId})
</insert>

2.模糊查询

<select id="listLike1" resultType="cn.sycoder.domain.Student">
    select * from student
    where name like concat('%',#{name},'%')
</select>
  • select * from student where name like ?

3.批量操作

3.1批量插入

  • 开启sqlSession 批处理 ExecutorType.BATCH,但是记得刷新 statements session.flushStatements();
try (SqlSession session = sqlSessionFactory.openSession(ExecutorType.BATCH,true)) {
       StudentMapper mapper = session.getMapper(StudentMapper.class);
       Student student = new Student();
       mapper.insert(student);
       Student student1 = new Student();
       mapper.insert(student1);
       List<BatchResult> batchResults = session.flushStatements();

} catch (Exception e) {
       e.printStackTrace();
}
  •  使用 foreach
<insert id="batchInsert" useGeneratedKeys="true" keyColumn="id" keyProperty="id">
    insert into student (name,age) values
    <foreach collection="list"  item="stu"  separator=",">
        (#{stu.name},#{stu.age})
    </foreach>
</insert>
int batchInsert(List<Student> list);

3.2批量删除

  • $(ids)

    @Delete("delete from student where id in(${ids})")
    int deleteBatch(String ids);
  • foreach

    <delete id="del">
        delete from student 
        <where>
            <foreach collection="ids"  item="id" index="i" open="id in(" close=")" separator=",">
                #{id}
            </foreach>
        </where>
    </delete>

    3.3批量修改(用处不大)

  • 如果是给某一堆id 修改相同属性值,可以使用foreach

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

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

相关文章

【OpenFOAM】-olaFlow-算例10-wavemakerTank

算例路径&#xff1a; olaFlow\tutorials\wavemakerTank 算例描述&#xff1a; 采用 Flap和Piston两种方式的动网格进行造波 学习目标&#xff1a; 了解 olaDyMFlow 的使用&#xff1b;理解动网格使用和参数设置&#xff0c;理解 dynamicMotionSolverFvMesh 参数设置&#xff1…

ChatGPT对于普通人有什么机会和影响?

ChatGPT爆火“出圈”&#xff0c;短短三个月里&#xff0c;势如破竹。 月活已经达到1亿&#xff0c;什么概念呢&#xff1f;Tiktok在海外达到1亿月活用了将近9个月时间&#xff0c;Instagram用了大约2年半&#xff0c;就连比尔盖茨都表示“Web3没那么重要&#xff0c;元宇宙没…

STM32---备份寄存器BKP和 FLASH学习使用

BKP库函数 学习BKP&#xff0c;首先就是知道BKP每一个函数的作用然后如何使用即可 使用备份域的作用只需要操作上面的两个函数即可&#xff0c;其余的都是它的其他功能 BKP简介 备份寄存器是42个16位的寄存器&#xff0c;可用来存储84个字节的用户应用程序数据。他们处在备份…

【Jupyter Notebook的简单入门使用】

【Jupyter Notebook的简单入门使用】简单介绍安装与配置简单使用Markdown关闭简单介绍 Jupyter官网 Jupyter Notebook 介绍 简单来讲&#xff0c;它是一个网页应用&#xff0c;可以进行文档编写&#xff0c;甚至运行 py 代码等功能 安装与配置 下载合适版本的 python &#…

【C语言】带你彻底理解指针(1)

✨✨✨✨如果文章对你有帮助记得点赞收藏关注哦&#xff01;&#xff01;✨✨✨✨ 文章目录指针的介绍&#xff1a;一、简单指针&#x1f308;1.1 指针的定义与使用1.2 指针与数组二、指针数组✨三、数组指针&#x1f31e;3.1 数组指针的定义3.2 ”数组名“与”&数组名“3.…

达梦数据库DSC集群部署

一、概述 1.1 DSC 集群架构 1.2 架构说明 1、DMDSC 集群是一个多实例、单数据库的系统。 多个数据库实例可以同时访问、修改同一个数据库的数据。 2、数据文件、控制文件在集群系统中只有一份,不论有几个节点,这些节点都平等地使用这些文件, 这些文件保存在共享存储上。 3…

肠道核心菌属——双歧杆菌属,了解并拥有它

双歧杆菌 双歧杆菌属&#xff08;Bifidobacterium&#xff09;是放线菌门严格厌氧的革兰氏阳性多形性杆状细菌。末端常常分叉&#xff0c;故名双歧杆菌。是人和动物肠道的重要核心菌群和有益生理菌群&#xff0c;也是母乳喂养婴儿中发现的第二大菌。 肥胖、糖尿病和过敏等各种疾…

高德地图基础教程超详细版

在当前社会&#xff0c;对于地图的使用是很必须的&#xff0c;所以对于程序员来说也是需要掌握的技能&#xff0c;目前主流的又百度地图和高德地图&#xff0c;但是我建议使用高德地图&#xff0c;因为百度地图的API着实不好用吖&#xff0c;不好理解&#xff0c;对于开发人员来…

浏览器输入www.baidu.com后执行的全部过程

日升时奋斗&#xff0c;日落时自省 <1>URL输入 URL称为 : 统一资源定位符,用于定位互联网上的资源,也就是平常提起的"网址" 地址栏输入网址之后按下回车,浏览器会对输入的信息进行评判 (1)检查输入的内容是否是是一个合法的网址连接(非法地址不行) (2)合法的…

【spring教程】3.IoC容器概述

IoC 是 Inversion of Control 的简写&#xff0c;译为“控制反转”&#xff0c;它不是一门技术&#xff0c;而是一种设计思想&#xff0c;是一个重要的面向对象编程法则&#xff0c;能够指导我们如何设计出松耦合、更优良的程序。 Spring 通过 IoC 容器来管理所有 Java 对象的实…

【数据结构】二叉树的原理及实现

1.什么是数&#xff1f; 树这种数据结构在计算机中是非常重要的&#xff0c;是一种非线性数据结构。一些数据库的底层与快速索引都离不开树这种数据结构。树是有很多节点组成的具有一定层次关系的集合。最上面的可以看成是树的头&#xff0c;下面的很多节点就在这个头的基础上…

前端如何实现局部滚动效果?

一、基础版局部滚动 重点在于给需要滚动的区域加上 overflow: auto; 属性 废话不多说&#xff0c;先上基础版的局部滚动代码&#xff1a; <!DOCTYPE html> <html lang"en"> <head> <meta charset"UTF-8"> <meta http-equiv…

智能优化算法——遗传算法(GA)(纯理论,不包含代码)

今天接着PSO&#xff0c;记录一下遗传算法的实现原理。&#xff08;若有错误&#xff0c;请大佬帮忙指正&#xff01;&#xff09;&#xff08;同样&#xff0c;主要参考b站视频学习加入自己的一些理解&#xff0c;如果想要看视频学习&#xff0c;可以直接移步最后参考链接&…

深度学习引言

动手学深度学习pytorch版-笔记原文链接日常生活中的机器学习机器学习中的关键组件数据模型目标函数优化算法各种机器学习问题监督学习回归分类标记问题搜索推荐系统序列学习无监督学习与环境互动强化学习特点小结原文链接 动手学深度学习pytorch中文版 日常生活中的机器学习 …

可怕,chatGPT用3小时教会我数据分析

chatGPT这玩意真的是我的救星,用它作为我的Python教练,我用三个小时学会了数据处理(Pandas)和绘图(matplotlib)。 这两个库的学习,在之前已经困扰了我7个月。之前卡壳的原因,是我一直没有耐心从零开始,按照教材设置的教程去学习Python——我擅长在项目中学习,一点一点…

Android实现炫酷跳动的闪屏LOGO

前言&#xff1a;在日常开发中&#xff0c;经常会遇到各种视觉效果&#xff0c;有的效果可能一眼看去会让人觉得很复杂&#xff0c;但是我们必须明确一点&#xff1a;所有复杂动效都是可以分解成单一的基础动作&#xff0c;比如缩放&#xff0c;平移&#xff0c;旋转这些基础单…

最新BlackArch发布,提供1400款渗透测试工具

近日&#xff0c;BlackArch Linux新版本发布&#xff0c;此版本为白帽子和安全研究人员提供了大约1400款渗透测试工具&#xff0c;如果你是一位白帽子或者安全研究人员&#xff0c;这个消息无疑会让你很感兴趣。BlackArch Linux是一款基于Arch Linux的发行版&#xff0c;主要面…

luckysheet的使用——07.二次开发自动插入批注功能

在单元格编辑完成后&#xff0c;需要自动在这个单元格上新增批注&#xff0c;此时需要改造旧代码&#xff0c;首先找到路径为 src/controllers/postil.js的文件&#xff0c;找到新增批注时触发的方法&#xff0c;如下&#xff1a; 2.对方法进行改造&#xff0c;新增传入变量co…

深入探讨下,IPC产品与智能家居融合的无限开创性

IPC还有哪些新玩法&#xff1f;随着摄像头的应用场景增加&#xff0c;IPC作为一种能力&#xff0c;正在融入到越来越多的智能设备中&#xff0c;形成了一批富有创意的智能 IPC 融合类产品。 比如&#xff0c;扫地机结合智能 IPC 后&#xff0c;能实现可视化精准识别障碍物&…

C++实现日期类

文章目录前言1.日期类的功能分析1.大致分析2.接口设计2.具体实现1.日期类的成员函数和成员变量2.初始化(构造函数&#xff09;3.对日期进行天数推算4.比较相关的运算符重载5.前置后置自增或自减6.日期相减与流插入流提取1.日期相减2.重载流插入和流提取3.总结前言 之前介绍了C…