MyBatis常用动态sql大总结

简介

相信大家没用Mybatis之前,都碰到过各种条件判断拼接SQL、需要去掉多余的逗号等痛苦,Mybatis中的动态SQL能很好的解决上面说的情况,可以很灵活的组装SQL语句,从而提高开发效率。

1、SQL的动态拼接有哪些

  • if标签
  • where标签
  • choose when otherwise标签
  • set标签
  • trim标签
  • bind标签
  • sql和include标签 foreach标签

2、if标签:

test中写判断条件 参数直接paramN或者别名 特点: 只要成立就拼接在Sql语句中,都成立就全部都拼接 注意: where子句中加上1=1来规避and的风险

<select id="uid" resultType="UserEntity">
select * from UserEntity where 1=1
<if test="param1!=null and param1!=''">
and outno=#{param1}
</if>
<if test="param2!=null and param2!=''">
and inno=#{param2}
</if>
</select>

条件模糊查以及查询时间段内数据

<select id="uid" resultType="UserEntity">
select * from UserEntity where 1=1
<if test="param1!=null and param1!=''">
and outno=#{param1}
</if>
<if test="param2!=null and param2!=''">and inno LIKE CONCAT('%',#{param2 },'%' )
</if>
<if test="effectiveTime !=null and effectiveTime !=''">
and begin_time <= #{effectiveTime}
//effectiveTime 是封的查询条件类的查询字段  and end_time >= #{effectiveTime}
//begin_time,end_time 对应数据库字段。
</if>
</select>

3、where标签:

特点:

会自动地给Sql语句添加where关键字,并将第一个and去除。

<select id="uid" resultType="UserEntity">
    select * from UserEntity
    <where>
    <if test="param1!=null and param1!=''">
    and outno=#{param1}
    </if>
    <if test="param2!=null and param2!=''">
    and inno=#{param2}
    </if>
    </where>
   </select>

4、choose when otherwise标签

特点:

条件只要有一个成立,其他的就不会再判断了。

如果没有成立的条件则默认执行otherwise中的内容

<select id="uid" resultType="UserEntity">
select * from UserEntity
<where>
<choose>
<when test="param1!=null and param1!=''">
and outno=#{param1}
</when>
<when test="param2!=null and param2!=''">
and inno=#{param2}
</when>
<otherwise>
and 1=1
</otherwise>
</choose>
</where>
</select>

5、set标签:

产生一个set关键字,自动去除最后一个逗号。

注意: ​

在判断条件中最后保持有一个永远成立的条件。避免sql错误。

<update id="uid">
update accountTable
<set>
<if test="aname!=null and aname!=''">
aname=#{aname},
</if>
<if test="money !=null  and money !=''">
money=#{money},
</if>
<if test="ano !=null  and ano !=''">
ano=#{ano},
</if>
</set>
where  ano=#{ano}
</update>

6、trim标签:

prefix:在trim的内容前添加指定的内容 ​

prefixOverrides在trim的内容前去除指定的内容 ​

suffix:在trim的内容后添加指定的内容 ​

suffixOverrides:在trim的内容后去除指定的内容 ​

注意: ​

先去除后添加 ​

添加内容会默认添加一个空格。

<update id="upT" parameterType="account">
update account
<trim prefix="$" prefixOverrides="" suffix="" suffixOverrides="">
<if test="ano !=null  and ano !=''">
ano=#{ano},
</if>
<if test="aname!=null and aname!=''">
aname=#{aname},
</if>
<if test="money !=null  and money !=''">
money=#{money},
</if>
</trim>
where ano=#{ano}
</update>

7、bind标签:

name:参数名 ​

value:表达式,注意字符串拼接按照变量方式进行拼接 ​

例如:

 <bind name="money" value="'$'+money"/>

给参数重新赋值

<update id="upB" parameterType="account">
      <bind name="money" value="money+100"/>
    update account
    <trim prefix="set" suffixOverrides=",">
    <if test="ano !=null  and ano !=''">
    ano=#{ano},
    </if>
    <if test="aname!=null and aname!=''">
    aname=#{aname},
    </if>
    <if test="money !=null  and money !=''">
    money=#{money},
    </if>
     </trim>
    where ano=#{ano}
</update>

8、sql和include标签:

sql标签:在外部声明公用SQL语句 ​

id ​

include标签:引入声明的公共SQL语句 ​

refid: ​

优点:便于SQL的整体修改 ​

缺点:难于阅读

 <select id="selA" resultType="account">
    select <include refid="mysql"></include> from account
   </select>
   <sql id="mysql">
    ano,aname,apwd,money
   </sql>

9、foreach标签:

构造IN条件语句时需要对集合进行遍历,这时候可以使用foreach元素。foreach会去掉多余","。若集合为空,则不会执行foreach元素中的操作,但此时会多出"in"关键字,报错。

item:集合中的元素

index:元素所在集合的下标,迭代map时,index是键

collection:集合的类型,可选值list,array,除此之外还可以是@Param("name")、Map中的key、类的成员变量 open、

close:在首、尾拼接的字符

separator:每个元素间的分隔符

注: foreach标签支持List、Set、Map、Array等的遍历

迭代数组或者List、Set集合时,index是迭代次数,item是本次迭代获取的元素;

迭代Map(或Map.Entry对象的集合)时,index是键,item是值

collection属性介绍

传入单参数且是List时,collection="list"

传入单参数且是Array时,collection="array"

传入单参数且是Set时,需使用@Param注解,同下

传入单参数且使用@Param("name")时,collection="name",即和@Param注解的value属性值相同,此时list、array无效

传入多参数且封装成Map时,如map.put("ids", Arrays.asList(1, 2)),此时collection="ids"

传入多参数且封装成类时,如User类中有成员变量List roleIds,此时collection="roleIds";若User类中有成员变量Role role,Role类中有成员变量prilIds,此时collection="role.prilIds"

 <select id="selF" parameterType="list" resultType="account">
    select * from account where ano in
    <foreach collection="list" item="item" open="(" separator="," close=")">
    #{item}
    </foreach>
 </select>
   <insert id="inF">
    insert into log values
    <foreach collection="list"  item="log" separator=",">
    (#{log.outno},#{log.inno},#{log.money})
    </foreach>
   </insert>

10、示例

批量修改的动态sql

controller层

 /**
     * 批量修改
     */
    @PutMapping("/aaa")
    @ApiOperation(value = "下架")
    public R aaa(@RequestBody Asa asa) {
        this.goodTestService.updateState(asa.getIds(),asa.getMsg());
        return R.data("cg");
    }

service

package com.troy.testa.service;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.IService;
import com.troy.testa.dto.GoodTestDTO;
import com.troy.testa.entity.GoodTest;
import org.springframework.data.domain.Pageable;

import java.util.List;

/**
 * (GoodTest)表服务接口
 * @author zhangh
 * @date 2021-03-21 15:31:34
 */
public interface GoodTestService extends IService<GoodTest> {

    void updateState(String[] ids,String msg);
}

serviceImp

 @Override
    public void updateState(String[] ids,String msg) {

        baseMapper.updateState(ids,msg);
    }

dao

package com.troy.testa.dao;

import com.baomidou.mybatisplus.core.mapper.BaseMapper;

import com.troy.testa.dto.GoodTestDTO;
import com.troy.testa.entity.GoodTest;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
import com.baomidou.mybatisplus.core.metadata.IPage;
import java.util.List;

/**
 * (GoodTest)表数据库访问层
 * @author zhangh
 * @date 2021-03-21 15:31:34
 */
@Mapper
public interface GoodTestDao extends BaseMapper<GoodTest> {

    void updateState(@Param("ids") String[] ids,@Param("msg") String msg);
}

xml

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.troy.testa.dao.GoodTestDao">

    <update id="updateState">
        <foreach collection="ids" item="item" index="index" separator=";">
            UPDATE good_test
            SET good_state = 1,good_name=#{msg}
            WHERE id = #{item}
        </foreach>
    </update>

postman测试

表已批量修改

成功!

虽然可以用程序循环实现,但是用了动态sql少去了不少工作量。

总结:

发中,经常需要根据不同的条件动态拼接SQL,并且还确保空格、列名最后的逗号、多余的AND、OR条件等。在MyBatis中处理这种情况是比较方便容易的。

到此这篇关于MyBatis常用动态sql的文章就介绍到这了,更多相关MyBatis动态sql内容请搜索我们以前的文章或继续浏览下面的相关文章希望大家以后多多支持我们!

(0)

相关推荐

  • MyBatis执行动态SQL的方法

    大家基本上都知道如何使用 MyBatis 执行任意 SQL,使用方法很简单,例如在一个 XXMapper.xml 中: <select id="executeSql" resultType="map"> ${_parameter} </select> 你可以如下调用: sqlSession.selectList("executeSql", "select * from sysuser where enabled

  • MyBatis 动态拼接Sql字符串的问题

    MyBatis 的一个强大的特性之一通常是它的动态 SQL 能力.如果你有使用 JDBC 或其他 相似框架的经验,你就明白条件地串联 SQL 字符串在一起是多么的痛苦,确保不能忘了空格或在列表的最后省略逗号.动态 SQL 可以彻底处理这种痛苦. 动态SQL MyBatis的动态SQL,解决了SQL字符串拼接的痛苦. 1.if <select id="findActiveBlogWithTitleLike" parameterType="Blog" result

  • Mybatis中动态SQL,if,where,foreach的使用教程详解

    MyBatis的动态SQL是基于OGNL表达式的,它可以帮助我们方便的在SQL语句中实现某些逻辑. MyBatis中用于实现动态SQL的元素主要有: if choose(when,otherwise) trim where set foreach mybatis核心 对sql语句进行灵活操作,通过表达式进行判断,对sql进行灵活拼接.组装. 1.statement中直接定义使用动态SQL: 在statement中利用if 和 where 条件组合达到我们的需求,通过一个例子来说明: 原SQL语句

  • Mybatis模糊查询和动态sql语句的用法

    Mybatis 模糊查询和动态sql语句 模糊查询 对数据库最常用的操作就是查询了,但是如何使用Mybatis进行模糊查询呢?下面先看一个简单的模糊查询 <select id="select01" resultMap="BasicResultMap"> SELECT * FROM oa_employee WHERE emp_name LIKE #{asd} </select> 这是一条伪模糊查询, 因为没有实现真正的模糊 "%&qu

  • MyBatis动态Sql之if标签的用法详解

    最近在读刘增辉老师所著的<MyBatis从入门到精通>一书,很有收获,于是将自己学习的过程以博客形式输出,如有错误,欢迎指正,如帮助到你,不胜荣幸! 本篇博客主要讲解如何使用if标签生成动态的Sql,主要包含以下3个场景: 1.根据查询条件实现动态查询 2.根据参数值实现动态更新某些列 3.根据参数值实现动态插入某些列 1. 使用if标签实现动态查询 假设有这样1个需求:根据用户的输入条件来查询用户列表,如果输入了用户名,就根据用户名模糊查询,如果输入了邮箱,就根据邮箱精确查询,如果同时输入了

  • MyBatis 执行动态 SQL语句详解

    大家基本上都知道如何使用 MyBatis 执行任意 SQL,使用方法很简单,例如在一个 XXMapper.xml 中: <select id="executeSql" resultType="map"> ${_parameter} </select> 你可以如下调用: sqlSession.selectList("executeSql", "select * from sysuser where enabled

  • mybatis动态sql之Map参数的讲解

    mybatis 动态sql之Map参数 Mapper文件: <mapper namespace="com.cn.shoje.oa.modules.logistics.dao.PurcDao"> <select id="findAll" parameterType="Map" resultType="Purchase"> select * from prod_purchase where 1=1 <

  • Mybatis动态SQL之if、choose、where、set、trim、foreach标记实例详解

    动态SQL就是动态的生成SQL. if标记 假设有这样一种需求:查询用户,当用户名不等于"admin"的时候,我们还需要密码为123456. 数据库中的数据为: MyBatisConfig.xml <?xml version="1.0" encoding="UTF-8" ?> <!DOCTYPE configuration PUBLIC "-//mybatis.org//DTD Config 3.0//EN"

  • mybatis的动态sql详解(精)

    MyBatis 的一个强大的特性之一通常是它的动态 SQL 能力.如果你有使用 JDBC 或其他 相似框架的经验,你就明白条件地串联 SQL 字符串在一起是多么的痛苦,确保不能忘了空 格或在列表的最后省略逗号.动态 SQL 可以彻底处理这种痛苦. 通常使用动态SQL不可能是独立的一部分,MyBatis当然使用一种强大的动态SQL语言来改进这种情形,这种语言可以被用在任意映射的SQL语句中. 动态SQL元素和使用 JSTL或其他相似的基于XML的文本处理器相似.在MyBatis之前的版本中,有很多

  • MyBatis常用动态sql大总结

    简介 相信大家没用Mybatis之前,都碰到过各种条件判断拼接SQL.需要去掉多余的逗号等痛苦,Mybatis中的动态SQL能很好的解决上面说的情况,可以很灵活的组装SQL语句,从而提高开发效率. 1.SQL的动态拼接有哪些 if标签 where标签 choose when otherwise标签 set标签 trim标签 bind标签 sql和include标签 foreach标签 2.if标签: test中写判断条件 参数直接paramN或者别名 特点: 只要成立就拼接在Sql语句中,都成立

  • Mybatis之动态sql标签的使用

    1.Mybatis动态sql MyBatis 的强大特性之一便是它的动态 SQL.如果你有使用 JDBC 或其它类似框架的经验,你就能体会到根据不同条件拼接 SQL 语句的痛苦.例如拼接时要确保不能忘记添加必要的空格,还要注意去掉列表最后一个列名的逗号.利用动态 SQL 这一特性可以彻底摆脱这种痛苦. 虽然在以前使用动态 SQL 并非一件易事,但正是 MyBatis 提供了可以被用在任意 SQL 映射语句中的强大的动态 SQL 语言得以改进这种情形. 动态 SQL 元素和 JSTL 或基于类似

  • oracle+mybatis 使用动态Sql当插入字段不确定的情况下实现批量insert

    最近做项目遇到一个挺纠结的问题,由于业务的关系,DB的数据表无法确定,在使用过程中字段可能会增加,这样在insert时给我造成了很大的困扰. 先来看一下最终我是怎么实现的: <insert id="batchInsertLine" parameterType="HashMap"> <![CDATA[ INSERT INTO tg_fcst_lines(${lineColumn}) select result.*,sq_fcst_lines.next

  • mybatis的动态SQL和模糊查询实例详解

    现在以一个例子来介绍mybatis的动态SQL和模糊查询:通过多条件查询用户记录,条件为姓名模糊匹配,并且年龄在某两个值之间. 新建表d_user: create table d_user( id int primary key auto_increment, name varchar(10), age int(3) ); insert into d_user(name,age) values('Tom',12); insert into d_user(name,age) values('Bob

  • MyBatis使用动态SQL标签的小陷阱

    MyBatis是一个支持普通SQL查询,存储过程和高级映射的优秀持久层框架.MyBatis消除了几乎所有的JDBC代码和参数的手工设置以及对结果集的检索封装.MyBatis可以使用简单的XML或注解用于配置和原始映射,将接口和Java的POJO(Plain Old Java Objects,普通的Java对象)映射成数据库中的记录. 现在MyBatis越来越受大家的喜爱了,它的优势大家都知道,我就不多说了,直接说重点. MyBatis中提供动态SQL功能,我们可以使用<if><when&

  • Fluent MyBatis实现动态SQL

    目录 数据准备 代码生成 在 WHERE 条件中使用动态条件 在 UPDATE 使用动态更新 choose 标签 参考 MyBatis 令人喜欢的一大特性就是动态 SQL.在使用 JDBC 的过程中, 根据条件进行 SQL 的拼接是很麻烦且很容易出错的, MyBatis虽然提供了动态拼装的能力,但这些写xml文件,也确实折磨开发.Fluent MyBatis提供了更贴合Java语言特质的,对程序员友好的Fluent拼装能力. Fluent MyBatis动态SQL,写SQL更爽 数据准备 为了后

随机推荐