广告
返回顶部
首页 > 资讯 > 数据库 >MyBatis动态SQL的示例
  • 219
分享到

MyBatis动态SQL的示例

2024-04-02 19:04:59 219人浏览 泡泡鱼
摘要

这篇文章将为大家详细讲解有关mybatis动态sql的示例,小编觉得挺实用的,因此分享给大家做个参考,希望大家阅读完这篇文章后可以有所收获。动态 SQLMyBatis 的强大特性之一便是它的动态 SQL。如

这篇文章将为大家详细讲解有关mybatis动态sql的示例,小编觉得挺实用的,因此分享给大家做个参考,希望大家阅读完这篇文章后可以有所收获。

动态 SQL

MyBatis 的强大特性之一便是它的动态 SQL。如果你有使用 JDBC 或其它类似框架的经验,你就能体会到根据不同条件拼接 SQL 语句的痛苦。例如拼接时要确保不能忘记添加必要的空格,还要注意去掉列表最后一个列名的逗号。利用动态 SQL 这一特性可以彻底摆脱这种痛苦。

虽然在以前使用动态 SQL 并非一件易事,但正是 MyBatis 提供了可以被用在任意 SQL 映射语句中的强大的动态 SQL 语言得以改进这种情形。

动态 SQL 元素和 jsTL 或基于类似 XML 的文本处理器相似。在 MyBatis 之前的版本中,有很多元素需要花时间了解。MyBatis 3 大大精简了元素种类,现在只需学习原来一半的元素便可。MyBatis 采用功能强大的基于 OGNL 的表达式来淘汰其它大部分元素。

准备

首先创建User实体类

public class User {
    private Integer id;
    private String username;
    private String userEmail;
    private String userCity;
    private Integer age;}

创建user表

CREATE TABLE user (
  id int(11) NOT NULL AUTO_INCREMENT,
  username varchar(255) DEFAULT NULL,
    user_email varchar(255) DEFAULT NULL,
    user_city varchar(255) DEFAULT NULL,
    age int(11) DEFAULT NULL,
  PRIMARY KEY (id))

if

定义接口方法

public List<User> findByUser(User user);

接口对应的 Mapper.xml 定义如下所示

<select id="findByUser" resultType="com.example.mybatis.entity.User">
    select
    id, username, user_email userEmail, user_city userCity, age
    from user
    where    <if test="username != null and username != ''">
        username = #{username}    </if>
    <if test="userEmail != null and userEmail != ''">
        and user_email = #{userEmail}    </if>
    <if test="userCity != null and userCity != ''">
        and user_city = #{userCity}    </if></select>

如果if标签上的test为true,那么if标签里面的SQL语句将会被拼接。

如果username、userEmail、userCity都不为空,那么SQL将会拼接成如下所示

select id, username, user_email userEmail, user_city userCity, age 
from user where username = ? and user_email = ? and user_city = ?

如果只有username不为空,那么SQL将会拼接成如下所示

select id, username, user_email userEmail, user_city userCity, age 
from user where username = ?

但是这种方式存在一个缺点,假设此时username为空,userEmail、userCity都不为空。

我们来分析动态 SQL 代码,现在没有给 username 赋值,即 username==null,所以 “username=#{username}” 这段代码不会添加到 SQL 语句中,那么最终拼接好的动态 SQL 是这样的:

select id, username, user_email userEmail, user_city userCity, age 
from user where and user_email = ? and user_city = ?

where 后面直接跟 and,很明显的语法错误,此时应该把紧跟在where后面的and删掉。为了解决这个问题,可以使用where标签。

where

将上面的SQL改成如下所示

    <select id="findByUser" resultType="com.example.mybatis.entity.User">
        select
        id, username, user_email userEmail, user_city userCity, age        from user
        <where>
            <if test="username != null and username != ''">
                username = #{username}
            </if>
            <if test="userEmail != null and userEmail != ''">
                and user_email = #{userEmail}
            </if>
            <if test="userCity != null and userCity != ''">
                and user_city = #{userCity}
            </if>
        </where>
    </select>

如果where标签里面的if标签有满足条件的,那么where标签就会被拼接成where语句,若if标签拼接的SQL最前面有and语句,那么这个and将会被删除。使用这种方法, 会自动删除SQL中不需要的关键字,所以一般 if 标签和 where 标签会组合起来使用。

trim

trim标签中的 prefixsuffix属性会被用于生成实际的 SQL 语句,会和标签内部的语句拼接。

如果语句的前面或后面遇到 prefixOverridessuffixOverrides属性中指定的值,MyBatis 会自动将它们删除。在指定多个值的时候,别忘了每个值后面都要有一个空格,保证不会和后面的 SQL 连接在一起。

prefix:给拼接的SQL语句加一个前缀

suffix:给拼接的SQL语句加一个后缀

prefixOverrides:拼接的SQL语句前面遇到 prefixOverrides,MyBatis 会自动将它们删除

suffixOverrides:拼接的SQL语句后面遇到 suffixOverrides,MyBatis 会自动将它们删除

下面使用trim标签来实现where标签的功能

<select id="findByUser" resultType="com.example.mybatis.entity.User">
        select
        id, username, user_email userEmail, user_city userCity, age
        from user        <trim prefix="where" prefixOverrides="and">
            <if test="username != null and username != ''">
                username = #{username}            </if>
            <if test="userEmail != null and userEmail != ''">
                and user_email = #{userEmail}            </if>
            <if test="userCity != null and userCity != ''">
                and user_city = #{userCity}            </if>
        </trim>
    </select>

如果username为空,userEmail和userCity不为空,那么if 标签拼接的SQL语句如下所示

and user_email = #{userEmail} and user_city = #{userCity}

因为trim标签设置了prefixOverrides=”and”,而上面的SQL前面有and语句,所以需要将上面的and语句删掉,又因为trim标签设置了prefix=”where”,所以需要在拼接的SQL语句前面加一个where语句

最后trim标签的SQL语句被拼接成如下所示

where user_email = #{userEmail} and user_city = #{userCity}

choose

有时我们不想应用到所有的条件语句,而只想从中择其一项。针对这种情况,MyBatis 提供了 choose 元素,它有点像 Java 中的 switch 语句。

<select id="findByUser" resultType="com.example.mybatis.entity.User">
        select
        id, username, user_email userEmail, user_city userCity, age
        from user        <where>
            <choose>
                <when test="username != null and username != ''">
                    username = #{username}                </when>
                <when test="userEmail != null and userEmail != ''">
                    and user_email = #{userEmail}                </when>
                <when test="userCity != null and userCity != ''">
                    and user_city = #{userCity}                </when>
            </choose>
        </where>
    </select>

set

set 标签用于 Update 操作,会自动根据参数选择生成 SQL 语句。

接口定义如下

public int updateUser(User user);

接口对应的 Mapper.xml 定义如下所示

<update id="updateUser" parameterType="com.example.mybatis.entity.User">
       update user       <set>
           <if test="username != null and username != ''">
               username=#{username},           </if>
           <if test="userEmail != null and userEmail != ''">
               user_email=#{userEmail},           </if>
           <if test="userCity != null and userCity != ''">
               user_city=#{userCity},           </if>
           <if test="age != null">
              age=#{age}           </if>
       </set>
       where id=#{id}    </update>

foreach

foreach 标签可以迭代生成一系列值

*用于 SQL 的 in 语句 *

接口定义如下所示

public List<User> getUsersByIds(List<Integer> ids);

接口对应的 Mapper.xml 定义如下所示

<!--
        collection: 指定要遍历的集合
            默认情况下
                如果为Collection类型的,key为collection;
                如果为List类型的,key为list
                如果是数组类型,key为array
            可以通过@Param("ids")来指定key
        item: 将当前遍历的元素赋值给指定的变量
        open: 给遍历的结果添加一个开始字符
        close: 给遍历的结果添加一个结束字符
        separator: 每个元素之间的分隔符
    --><select id="getUsersByIds"
        resultType="com.example.mybatis.entity.User">
    select * from user
    where id in    <foreach collection="list" item="id" open="(" close=")" separator=",">
        #{id}    </foreach></select>

用于批量插入

接口定义如下所示

public int addUserList(List<User> users);

接口对应的 Mapper.xml 定义如下所示

<insert id="addUserList"
        parameterType="com.example.mybatis.entity.User">
    insert into user
    (username, user_email, user_city, age)
    values    <foreach item="user"  collection="list" separator=",">
        (#{user.username}, #{user.userEmail}, #{user.userCity}, #{user.age})    </foreach></insert><!--返回自增主键--><insert id="addUserList"
        parameterType="com.example.mybatis.entity.User"
        useGeneratedKeys="true"
        keyProperty="id">
    insert into user
    (username, user_email, user_city, age)
    values    <foreach item="user"  collection="list" separator=",">
        (#{user.username}, #{user.userEmail}, #{user.userCity}, #{user.age})    </foreach></insert><!--还可以这样写--><!--
    这种方式需要数据库连接属性设置allowMultiQueries=true
    这种分号分隔多个SQL还可以用于其他的批量操作,如修改、删除
--><insert id="addUserList"
        parameterType="com.example.mybatis.entity.User">
    <foreach item="user"  collection="list" separator=";">
        insert into user
        (username, user_email, user_city, age)
        values
        (#{user.username}, #{user.userEmail}, #{user.userCity}, #{user.age})    </foreach></insert><!--如果是oracle数据库,则需要这样写--><insert id="addUserList"
        parameterType="com.example.mybatis.entity.User">
    <foreach item="user" open="begin" close="end;"  collection="list">
        insert into user
        (username, user_email, user_city, age)
        values
        (#{user.username}, #{user.userEmail}, #{user.userCity}, #{user.age});    </foreach></insert>

关于MyBatis动态SQL的示例就分享到这里了,希望以上内容可以对大家有一定的帮助,可以学到更多知识。如果觉得文章不错,可以把它分享出去让更多的人看到。

您可能感兴趣的文档:

--结束END--

本文标题: MyBatis动态SQL的示例

本文链接: https://www.lsjlt.com/news/53766.html(转载时请注明来源链接)

有问题或投稿请发送至: 邮箱/279061341@qq.com    QQ/279061341

本篇文章演示代码以及资料文档资料下载

下载Word文档到电脑,方便收藏和打印~

下载Word文档
猜你喜欢
  • MyBatis动态SQL的示例
    这篇文章将为大家详细讲解有关MyBatis动态SQL的示例,小编觉得挺实用的,因此分享给大家做个参考,希望大家阅读完这篇文章后可以有所收获。动态 SQLMyBatis 的强大特性之一便是它的动态 SQL。如...
    99+
    2022-10-18
  • Mybatis动态SQL的示例代码
    目录基本流程IF,WhereSetChoose(when,otherwise)SQL片段总结什么是动态SQL:动态SQL就是根据不同的条件生成不同的SQL语句 基本流程 ...
    99+
    2022-11-12
  • Mybatis中xml的动态sql实现示例
    目录动态SQL简介一、#{}与${}区别#{}表示一个占位符,使用占位符可以防止sql注入,二、传递包装类型三、动态sql—类型四、动态sql—详解(一)if...
    99+
    2022-11-13
  • mybatis-plus动态表名的实现示例
    背景 在分表的背景下,有时候查询数据的时候需要跨表查询,那此时就需要MP在解析的时候,能够很好的自适应表格名称 实现 MP中是通过PaginationInterceptor(分页插件...
    99+
    2022-11-12
  • 【MyBatis框架】动态SQL
    MyBatis之动态SQL 目录 MyBatis之动态SQL1. < if > 元素2. < where >3. < choose >,< when >,< otherwise >元素4. < trim >元素5. < s...
    99+
    2023-08-30
    mybatis sql java 数据库 mysql
  • mybatis中的动态sql问题
    目录1、if(常用)2、where3、trim4.choose、when、otherwise5、foreach5.1批量删除5.2批量添加6、sql标签总结Mybatis框...
    99+
    2023-02-27
    mybatis动态sql 动态sql mybatis sql
  • MyBatis系列:(5)动态SQL
    1、动态SQL操作之查询查询条件不确定,需要根据情况产生SQL语法,这种情况叫动态SQL    <select id="dynamicFin...
    99+
    2022-10-18
  • Fluent MyBatis实现动态SQL
    目录数据准备代码生成在 WHERE 条件中使用动态条件在 UPDATE 使用动态更新choose 标签参考MyBatis 令人喜欢的一大特性就是动态 SQL。在使用 ...
    99+
    2022-11-12
  • mybatis的动态SQL和模糊查询实例详解
    现在以一个例子来介绍mybatis的动态SQL和模糊查询:通过多条件查询用户记录,条件为姓名模糊匹配,并且年龄在某两个值之间。 新建表d_user: create table d...
    99+
    2022-11-11
  • MyBatis 动态SQL和缓存机制实例详解
    有的时候需要根据要查询的参数动态的拼接SQL语句常用标签:- if:字符判断- choose【when...otherwise】:分支选择- trim【where,set】:字符串截取,其中where标签封装查询条件,s...
    99+
    2023-05-31
    mybatis 动态sql 缓存机制
  • 怎么分析mybatis的动态SQL
    这期内容当中小编将会给大家带来有关怎么分析mybatis的动态SQL,文章内容丰富且以专业的角度为大家分析和叙述,阅读完这篇文章希望大家可以有所收获。1、动态SQL:if 语句根据 username 和 sex 来查询数据。如果userna...
    99+
    2023-06-28
  • MyBatis动态SQL怎么实现
    这篇文章主要介绍了MyBatis动态SQL怎么实现的相关知识,内容详细易懂,操作简单快捷,具有一定借鉴价值,相信大家阅读完这篇MyBatis动态SQL怎么实现文章都会有所收获,下面我们一起来看看吧。mybatis最强大的功能之一便是它的动态...
    99+
    2023-06-30
  • 如何掌握MyBatis动态SQL
    这篇文章主要介绍“如何掌握MyBatis动态SQL”,在日常操作中,相信很多人在如何掌握MyBatis动态SQL问题上存在疑惑,小编查阅了各式资料,整理出简单好用的操作方法,希望对大家解答”如何掌握MyBa...
    99+
    2022-10-18
  • MyBatis动态SQL怎么使用
    今天小编给大家分享一下MyBatis动态SQL怎么使用的相关知识点,内容详细,逻辑清晰,相信大部分人都还太了解这方面的知识,所以分享这篇文章给大家参考一下,希望大家阅读完这篇文章后有所收获,下面我们一起来了解一下吧。MyBatis 框架动态...
    99+
    2023-06-29
  • MyBatis 动态SQL全面详解
    目录前言动态sql1.先看一下模块目录结构 2.物理建模和逻辑建模 3. 引入依赖 4.全局配置文件5.sql共性抽取文件 6.mapper接口 if静态sql:动态sql:wher...
    99+
    2022-11-12
  • Mybatis中的动态SQL语句解析
    这篇文章主要介绍了Mybatis中的动态SQL语句解析,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下   Mybatis中配置SQL有两种方式,一种是利用...
    99+
    2022-10-18
  • MyBatis-Plus动态返回实体类示例详解
    目录1. 自定义SqlSession2. 自定义SqlSessionFactory3. 自定义SqlSessionTemplate4. 自定义基础Mapper5. 使用1. 自定义S...
    99+
    2022-11-13
  • MyBatis常用动态sql大总结
    简介 相信大家没用Mybatis之前,都碰到过各种条件判断拼接SQL、需要去掉多余的逗号等痛苦,Mybatis中的动态SQL能很好的解决上面说的情况,可以很灵活的组装SQL语句,从...
    99+
    2022-11-12
  • Mybatis动态sql超详细讲解
    目录1、多表关联的嵌套查询2、注解3、动态sql1.if where2.trim3.choose when otherwise4.set5.foreach4、特殊符号处理5...
    99+
    2023-05-17
    mybatis动态sql mybatis 动态sql
  • Mybatis——动态SQL foreach批量操作
    动态SQL Foreach批量操作 前言前置必要知识MySQL批量插入MySQL批量查询MySQL批量修改MySQL批量删除 使用mybatis中的foreach进行批量操作foreach...
    99+
    2023-09-04
    mybatis sql mysql
软考高级职称资格查询
编程网,编程工程师的家园,是目前国内优秀的开源技术社区之一,形成了由开源软件库、代码分享、资讯、协作翻译、讨论区和博客等几大频道内容,为IT开发者提供了一个发现、使用、并交流开源技术的平台。
  • 官方手机版

  • 微信公众号

  • 商务合作