MyBatis 动态SQL
很多时候得根据需要去拼接SQL,MyBatis提供一些基本的元素支持在映射XML文件里面配置动态组装SQL
| 元素 | 作用 | 备注 |
| if | 判断语句 | 单条件分支判断 |
| choose(when、otherwise) | 相当于 数据库中的 case when | 多条件分支 |
| trime(where、set) | 辅助元素 | 处理SQL拼装问题 |
| for | 循环语句 | 在in语句等列举条件中常用 |
if元素
最常用的判断语句,常常与 test 属性联合使用
<select id="listWhere" resultType="map"> select uname,email,address from t_user
where 1=1 <if test="uname != '' and uname != null"> and uname linke concat('%',#{uname},'%') </if> <if test="email != '' and email != null"> and email = #{email} </if> </select>
choose、when、otherwise 元素
对应java中 switch case default
<select id="listWhere" resultType="map"> select uname,email,address from t_user where 1=1 <choose> <when test="address = 'a'"> and address = 'b' </when> <when test="address = 'b'"> and address = 'c' </when> <otherwise> and address is not null </otherwise> </choose> </select>
trim、 where、set元素
使用where元素,可以不用再设置 where 1=1 条件
<select id="listWhere" resultType="map"> select uname,email,address from t_user <where> <if test="uname != '' and uname != null"> and uname like concat('%',#{uname},'%') </if> </where> </select>
trim 元素作用是去掉一些特殊的字符串
prefix:代表的是语句的前缀
prefixOverrides:代表的是你需要去掉的那种字符串
<select id="listWhere" resultType="map"> select uname,email,address from t_user <trim prefix="where" prefixOverrides="and"> <if test="uname !=null and uname != ''"> and uname like concat('%',#{uname},'%') </if> </trim> </select>
set 一般用来实现单个字段的更新,set元素中,如果遇到了逗号,他会把对应的逗号去掉
注意 因为set元素删除了逗号,当set中的if条件如果有1个以上成立,就会导致sql语法错误
<update id="updateSingle" parameterType="SystemUser"> update t_table <set> <if test="uname != null and uname != ''"> uname = #{uname} </if> <if test="email != null and email != ''"> email = #{email} </if> </set> where id = #{id} </update>
foreach元素
是一个循环语句能够遍历集合,支持数组、List、Set接口的集合,对此提供遍历的功能
xml映射:
<select id="selectIn" resultType="SystemUser" > select * from t_user where address in <foreach collection="collection" item="item" index="index" open="(" separator="," close=")"> #{item} </foreach> </select>
- collection配置的collection 是别名,这里一般配置传递进来的参数名
- item配置在循环中存放当前元素的变量名, 默认名称为item
- index配置在当前循环中存放索引值的变量名,默认名称为index
- open和close配置的是以什么符号将这些元素包装起来
- separator配置的是各个元素的间隔字符
Mapper接口:
List<SystemUser> selectIn(List<String> address);
业务调用:
List<String> address = Arrays.asList("新疆","湖北","西藏");
this.systemUserMapper.selectIn(address);
输出的SQL日志:
SystemUserMapper.selectIn: ==> Preparing: select * from t_user where address in ( ? , ? , ? ) SystemUserMapper.selectIn: ==> Parameters: 新疆(String), 湖北(String), 西藏(String) SystemUserMapper.selectIn: <== Total: 0
bind元素
bind 元素的作用是通过OGNL表达式去自定义一个上下文变量,这样更方便我们使用
<select id="listWhere" resultType="map"> <bind name="unameLikeStr" value="'%' + uname + '%'" /> select uname,email,address from t_user where and uname like #{unameLikeStr} </select>

浙公网安备 33010602011771号