动态SQL

动态SQL
用户对查询条件的输入,存在不确定性,全不输,输全部,输一个,输多个,并且是模糊查询
如果是JDBC开发,需要对用户的输入进行判断并且要拼接sql,麻烦
mybatis提供了动态sql,来解决对各种sql的判断拼接问题


1.if条件判断
语法: <if test="条件"><if> 如果test的值为true,被if标签包含的sql会拼接

public List<Message> selectOne(@Param("command") String command, @Param("description") String description)
==========
<select>
select * from message 
<where>
<if test="command!=null and command!=''">
and command like "%" #{command} "%"
</if>
<if test="description!=null and description!=''">
and description like "%" #{description} "%"
</if>
</where>

order by mid limit #{currIndex},#{pageSize}
</select>

 

如果条件是数值型,test条件中,要具体的数字进行比较,不需要判断空‘’
如果条件是字符串类型,test条件中,要做非空判断,和非空串判断
如果条件是其他引用条件,test只做非空判断
2.where标签
if标签的补充,mybatis利用它可以智能的去掉不符合条件的sql中的and或者or
同时此标签可以在sql中智能的生成where单词
3。foreach
主要用来循环拼接sql,在需要in子句时,
批量插入,批量更新
delete from message where mid in(1,3,5)
slect * from message where command like '%' #{command} '%' and mid in(4,6,5)
如果是单参数,我们可以把批量数据封装成List或者数组
如果是多个参数,需要把数据封装成Map
语法:
<foreach collection="" item="" index="" separate="" open="" close="">
拼接的sql值
</foreach>
clooection的值
如果封装成collection或者List,那么collection的值为list
如果封装成数组,那么collection的值为array
如果封装成Map,那么collection的值指向的是你Map中需要循环的数据对应的key

posted @ 2020-08-24 15:40  龙陌  阅读(324)  评论(0编辑  收藏  举报