动态 SQL的作用:可以很方便地根据不同条件拼接 SQL 语句
准备:
在里面定义所需要用到的方法
一、if以及where
我们要调用select方法,通过name、mobile字段查询表中数据,但是这两个参数都有可能传入null,这时我们需要在xml文件中判断传入的参数是否为null,如果不为null则将其拼接成SQL语句,在test属性中设置判断条件,where 元素只会在至少有一个子元素的条件返回 SQL 子句的情况下才去插入“where”子句;而且,若语句的开头为“and”或“or”,where 元素也会将它们去除,:
for (UserInfo ui : userInfoDao.select("1","")) {
System.out.println(ui);
}
二、for each
foreach元素用于对一个集合进行遍历,构建 IN 条件语句时常用该元素;foreach 元素允许指定一个集合,声明可以在元素体内使用的集合项(item)和索引(index)变量,也允许指定开头与结尾的字符串以及在迭代结果之间放置分隔符。注意:可以将任何可迭代对象(如 List、Set 等)、Map 对象或者数组对象传递给 foreach 作为集合参数;当使用可迭代对象或者数组时,index 是当前迭代的次数,item 的值是本次迭代获取的元素;当使用 Map 对象(或者 Map.Entry 对象的集合)时,index 是键,item 是值。
<delete id="delete">
delete from user_info where id in
<foreach item="id" collection="ids" open="(" separator="," close=")">
#{id}
</foreach>
</delete>
System.out.println(userInfoDao.delete(new int[] {2,3}));
三、set
set 元素可以用于动态包含需要更新的列,而删掉无关的逗号
<update id="update">
update user_info
<set>
<if test="name!=null">
name=#{name},
</if>
<if test="mobile!=null">
mobile=#{mobile},
</if>
</set>
where id=#{id}
</update>
System.out.println(userInfoDao.update(3,"%a%", null));
来源:CSDN
作者:weixin_45516375
链接:https://blog.csdn.net/weixin_45516375/article/details/104804938