mybatis的mapper特殊字符转移以及动态SQL条件查询

kenx
• 阅读 1351

前言

我们知道在项目开发中之前使用数据库查询,都是基于jdbc,进行连接查询,然后是高级一点jdbcTemplate进行查询,但是我们发现还是不是很方便,有大量重复sql语句,与代码偶合,效率低下,于是就衍生出来ORM框架,如Mybatis,Hibernate,还有SpringBoot的,Spring Data JPA

条件查询

我们知道在mybatis mapper文件中条件查询符,如>=,<,之类是不能直接写的会报错的需要转移一下 如下图表

mybatis的mapper特殊字符转移以及动态SQL条件查询

详细内容参考

常见的条件查询操作有

mybatis的mapper特殊字符转移以及动态SQL条件查询

我们通过mybatis 提供的特有标签进行条件判断,达到动态拼接sql语句

if标签 where标签 choose when otherwise标签 foreach标签

快速入门

if标签

语法:

<if test="xxx != null and xxx != ''">

test中写判断条件 参数直接paramN或者别名 多个条件使用and或者or连接

只要条件成立就拼接在Sql语句中,都成立就全部都拼接

注意where子句中加上1=1来规避and的风险

如下例子:

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

where标签

对上面if标签条件判断where连接做了处理会自动的给Sql语句添加where关键字,并将第一个and去除

上面sql可以改造成如下:

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

</select>

choose when otherwise标签

类似于Java语法中的,case,switch语句判断

条件只要有一个成立,其他的就不会再判断了。如果没有成立的条件则默认执行otherwise中的内容

上面sql可以改造成如下:

<select id="selg" resultType="log">
      select * from log 
  <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>

foreach标签

语法:

  <foreach collection="idList" item="id" open="(" separator="," close=")">
</foreach>
  1. collection:要遍历的集合对象
  2. item:记录每次遍历的结果
  3. open:在结果的左边添加内容
  4. separator:结果和结果之间的内容
  5. close:在最后添加的内容

常用于in查询,和批量插入操作 如下案例:

<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="insertBatch">
        INSERT INTO t_user
        (id, name, password)
        VALUES
        <foreach collection ="userList" item="user" separator =",">
            (#{user.id}, #{user.name}, #{user.password})
        </foreach >
    </insert>

其他标签使用参考点击进入·

场景案例

  1. 当我们需要对多张表的关联数据进行复杂动态条件查询的时候,就需要用到 if标签进行判断 如下

根据用户手机号姓名年龄性别,等进行动态条件检索,这个时候我们需要动态通过调节去拼接sql 当条件满足sql语句加上对应条件差许

<select id="findUsersByUser" resultType="cn.soboys.kmall.sys.entity.User">
        select tu.USER_ID,tu.USERNAME,tu.SSEX,td.DEPT_NAME,tu.MOBILE,tu.EMAIL,tu.STATUS,tu.CREATE_TIME,
        td.DEPT_ID
        from t_user tu left join t_dept td on tu.DEPT_ID = td.DEPT_ID
        where tu.ADMIN_TYPE_ID  &gt;= 0 AND tu.ADMIN_TYPE_ID  &lt;= #{userParams.adminType}
        <if test="userParams.roleId != null and userParams.roleId != ''">
           and (select group_concat(ur.ROLE_ID)
            from t_user u
            right join t_user_role ur on ur.USER_ID = u.USER_ID,
            t_role r
            where r.ROLE_ID = ur.ROLE_ID
            and u.USER_ID = tu.USER_ID and r.ROLE_ID=#{userParams.roleId})
        </if>


        <if test="userParams.mobile != null and userParams.mobile != ''">
            AND tu.MOBILE =#{userParams.mobile}
        </if>
        <if test="userParams.username != null and userParams.username != ''">
            AND tu.USERNAME   like CONCAT('%',#{userParams.username},'%')
        </if>
        <if test="userParams.ssex != null and userParams.ssex != ''">
            AND tu.SSEX  =#{userParams.ssex}
        </if>
        <if test="userParams.status != null and userParams.status != ''">
            AND tu.STATUS =#{userParams.status}
        </if>
        <if test="userParams.deptId != null and userParams.deptId != ''">
            AND td.DEPT_ID =#{userParams.deptId}
        </if>
        <if test="userParams.createTime != null and userParams.createTime != ''">
            AND DATE_FORMAT(tu.CREATE_TIME,'%Y%m%d') BETWEEN substring_index(#{userParams.createTime},'#',1) and substring_index(#{userParams.createTime},'#',-1)
        </if>
    </select>

对应mapper对应的方法

<T> IPage<User> findUsersByUser(Page<T> page, @Param("userParams") SearchUserParams userParams);

对应参数实体对象

@Data
public class SearchUserParams {
    private String username;
    private String mobile;
    private String status;
    private String ssex;
    private Long deptId;
    private String createTime;
    private long adminType;
    private String roleId;
}

通过if标签去判断条件是否满足,满足就拼接对应sql

注意在上面我们提到的条件拼接第一个是where连接,而不是and应规避and风险保证sql语法正确 如下

<select id="findSearchCouponsPage" parameterType="cn.soboys.kmall.bean.web.params.SearchCouponParams" resultType="coupon">
        select *
        from coupon c
        left join user_coupon uc on c.coupon_id = uc.coupon_id
        WHERE 1 = 1
        <if test="couponParams.userId != null and couponParams.userId != ''">
           and uc.user_id =#{couponParams.userId}
        </if>
        <if test="couponParams.status != null and couponParams.status != ''">
            and c.status =#{couponParams.status}
        </if>
        <if test="couponParams.couponId != null and couponParams.couponId != ''">
            and c.coupon_id =#{couponParams.couponId}
        </if>
        <if test="couponParams.couponType != null and couponParams.couponType != ''">
            and c.type =#{couponParams.couponType}
        </if>
    </select>

我们可以通过假定给他一个默认条件 WHERE 1 = 1来解决,也可以通过嵌套where标签来解决

点赞
收藏
评论区
推荐文章
blmius blmius
2年前
MySQL:[Err] 1292 - Incorrect datetime value: ‘0000-00-00 00:00:00‘ for column ‘CREATE_TIME‘ at row 1
文章目录问题用navicat导入数据时,报错:原因这是因为当前的MySQL不支持datetime为0的情况。解决修改sql\mode:sql\mode:SQLMode定义了MySQL应支持的SQL语法、数据校验等,这样可以更容易地在不同的环境中使用MySQL。全局s
Jacquelyn38 Jacquelyn38
2年前
2020年前端实用代码段,为你的工作保驾护航
有空的时候,自己总结了几个代码段,在开发中也经常使用,谢谢。1、使用解构获取json数据let jsonData  id: 1,status: "OK",data: 'a', 'b';let  id, status, data: number   jsonData;console.log(id, status, number )
皕杰报表之UUID
​在我们用皕杰报表工具设计填报报表时,如何在新增行里自动增加id呢?能新增整数排序id吗?目前可以在新增行里自动增加id,但只能用uuid函数增加UUID编码,不能新增整数排序id。uuid函数说明:获取一个UUID,可以在填报表中用来创建数据ID语法:uuid()或uuid(sep)参数说明:sep布尔值,生成的uuid中是否包含分隔符'',缺省为
Easter79 Easter79
2年前
sql注入
反引号是个比较特别的字符,下面记录下怎么利用0x00SQL注入反引号可利用在分隔符及注释作用,不过使用范围只于表名、数据库名、字段名、起别名这些场景,下面具体说下1)表名payload:select\from\users\whereuser\_id1limit0,1;!(https://o
Stella981 Stella981
2年前
Python3:sqlalchemy对mysql数据库操作,非sql语句
Python3:sqlalchemy对mysql数据库操作,非sql语句python3authorlizmdatetime2018020110:00:00coding:utf8'''
Stella981 Stella981
2年前
PostgreSQL死锁进程及慢查询处理
1、死锁进程查看:SELECTFROMpg_stat_activityWHEREdatname'数据库名称'andwaitingtrue;pid进程id。2、慢查询SQL:selectdatname,pid,usename,application_name,client_addr,client
Wesley13 Wesley13
2年前
mysql5.6 分页查询优化
mysql5.6分页查询优化场景:表结构:主键(非自增)contentCode(varchar),过滤条件列为updateTime(timeStamp),已经为timestamp建立索引。搜索sql为:SELECTFROMmy_hello_tableWHEREupdat
Stella981 Stella981
2年前
Django中Admin中的一些参数配置
设置在列表中显示的字段,id为django模型默认的主键list_display('id','name','sex','profession','email','qq','phone','status','create_time')设置在列表可编辑字段list_editable
Wesley13 Wesley13
2年前
MySQL部分从库上面因为大量的临时表tmp_table造成慢查询
背景描述Time:20190124T00:08:14.70572408:00User@Host:@Id:Schema:sentrymetaLast_errno:0Killed:0Query_time:0.315758Lock_
Python进阶者 Python进阶者
3个月前
Excel中这日期老是出来00:00:00,怎么用Pandas把这个去除
大家好,我是皮皮。一、前言前几天在Python白银交流群【上海新年人】问了一个Pandas数据筛选的问题。问题如下:这日期老是出来00:00:00,怎么把这个去除。二、实现过程后来【论草莓如何成为冻干莓】给了一个思路和代码如下:pd.toexcel之前把这