APP下载

Mybatis必会的动态SQL

消息来源:baojiabao.com 作者: 发布时间:2026-05-19

报价宝综合消息Mybatis必会的动态SQL

前言

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

Mybatis动态sql

mybatis 动态SQL,通过 if, choose, when, otherwise, trim, where, set, foreach等标签,可组合成非常灵活的SQL语句,从而在提高 SQL 语句的准确性的同时,也大大提高了开发人员的效率。本文主要介绍这几个动态SQL.

具体示例

if标签 if就是用来对输入对映的字段进行判断 一般是非空判断 null 和。

!--案例1:动态sql之if--

selectid=selectUsersIfparameterType=userresultType=user

select*fromuserswhere1=1

iftest=uname!=nullanduname!=\'\'andunamelike%#{uname}%/if

iftest=sex!=nullandsex!=\'\'andsex=#{sex}/if

/select

动态SQL where / 相当于 where关键字 where /可以自动处理第一个前and 或者or。 当条件都没有的时候 where也不会加上 。

!--案例2:动态sql之where可以自动处理第一个前and或者or。当条件都没有的时候where也不会加上--

selectid=selectUsersWhereparameterType=userresultType=user

select*fromusers

where

iftest=uname!=nullanduname!=\'\'andunamelike%#{uname}%/if

iftest=sex!=nullandsex!=\'\'andsex=#{sex}/if

/where

choose—when--when--otherwise when可以多个 otherwise只能有一个 类似于 switch case。

需求:输入使用者id 按照使用者id进行精确查询 其他条件不看 没有输入 id 使用者名称模糊查询 都没有的话 查询id=1的使用者

!--案例3:动态sql之choose—whenwhenotherwise--

selectid=selectUsersChooseparameterType=userresultType=user

select*fromusers

where

choose

whentest=uid!=nulluid=#{uid}/when

whentest=uname!=nullanduname!=\'\'unamelike%#{uname}%/when

otherwiseuid=1/otherwise

/choose

/where

/select

动态sql之set 代替set关键字 set标签可以帮助我们去掉最后一个逗号

updateid=updateSetparameterType=user

updateusers

set

iftest=uname!=nullanduname!=\'\'uname=#{uname},/if

iftest=upwd!=nullandupwd!=\'\'upwd=#{upwd},/if

iftest=sex!=nullandsex!=\'\'sex=#{sex},/if

iftest=birthday!=nullbirthday=#{birthday},/if

/set

whereuid=#{uid}

/update

Trim,trim代替where

!--案例5:动态sql之trim代替where--

selectid=selectUsersTrimWhereparameterType=userresultType=user

select*fromusers

!--

prefix:指新增字首修饰

suffix:新增字尾修饰

prefixOverrides:去掉字首修饰

suffixOverrides:去掉字尾修饰

--

trimprefix=whereprefixOverrides=and|or

iftest=uname!=nullanduname!=\'\'andunamelike%#{uname}%/if

iftest=sex!=nullandsex!=\'\'andsex=#{sex}/if

/trim

/select

Trim代替set:

!--案例6:动态sql之trim代替set--

updateid=updateTrimSetparameterType=user

updateusers

trimprefix=setsuffixOverrides=,suffix=whereuid=#{uid}

iftest=uname!=nullanduname!=\'\'uname=#{uname},/if

iftest=upwd!=nullandupwd!=\'\'upwd=#{upwd},/if

iftest=sex!=nullandsex!=\'\'sex=#{sex},/if

iftest=birthday!=nullbirthday=#{birthday},/if

/trim

Foreach来遍历集合

!--案例7:动态sql之foreach遍历阵列--

selectid=selectUsersForeachArrayresultType=user

select*fromuserswhereuidin

!--

collection:要遍历的集合

item:当前正在遍历的物件的变数名

open:开始遍历

close:结束便利

index:下标

separator:分割

--

foreachcollection=arrayitem=itemopen=(close=)index=indexseparator=,

#{item}

/foreach

/select

总结

熟练掌握以上Mysql的动态SQL,我们可以更得心应手的完成我的功能,写更少的程式码,实现更多的功能。

2020-01-02 05:49:00

相关文章