Mybatis动态 sql用法

动态顾名思义就是数据不是静态的,不是被写死的,他是可以根据需求随时改变的SQL语句。比如用查询来说,用户的需求千变万化,可是Mybatis提供给我们的方法却可以统一实现,这就是动态Sql的知识。本篇用SqlMapper.xml文件来演示各种用到的标签。

1. if 元素判断语句,单条件分支判断

         <if test="字段 != null">
             and 字段=#{字段}
         </if>
         
         <if test="字段!=0">
             and 字段=#{字段}
         </if>

2. where 

<where>
             <if test="ssex != null">
                 ssex=#{ssex}
             </if>
             <if test="classid !=0">
                 and classid=#{classid}
             </if>
         </where>

注意:

 1. 没有条件满足 就没有where和and
 2. 有一个条件满足 就自动加上where 和第一个条件的and可以不加第一个and where会自动添加  
 3. 有多个条件满足 就自动加上 where 和第二个以后的and

3.set 专门用在update中的标签
             <set>
             <if test="字段1!= null">
                 字段1=#{字段1},
             </if>
         
             <if test="字段2 !=0">
                 字段2 =#{字段2 },
             </if>
         </set>

4. trim 万能标签

<trim prefix="" suffix="" suffixOverrides="" prefixOverrides=""></trim>

prefix:开始要拼接的字句

suffix:结束要拼接的字句

suffixOverrides:结束要去掉的字句

prefixOverrides:开始要去掉的字句

<trim prefix="where" prefixOverrides="and">
             <if test="字段1!= null">
                 and 字段1=#{字段1}
             </if>
             <if test="字段2!=0">
                 and 字段2=#{字段2}
             </if>
         </trim>

5.foreach 循环的用法

<foreach collection="list" item="item" index="index" open="" close="" separator=";">

item:循环中的元素

collection:方法传递的参数,数组或者集合

open:以什么符号开始包裹

close:以什么符号结束包裹

separator:各个元素的间隔符号

index:循环元素的下标

        <foreach collection="array(数组)list(集合)" item="字段" open="(" close=")" separator=",">
             #{字段}
         </foreach>

6.bind 主要用来进行模糊查询

首先先介绍几种不用bind的模糊查询;

第一种:select * from student where sanme like #{v} ,这种方式不能防止sql非法注入,也不能进行前后模糊

第二种:select * from student where sanme like concat(#{v},'%'),属于我最喜欢的方式,因为在数据库中也可以使用concat拼接字符串

第三种:select * from student where sanme like '${v}%',可以模糊查询,但不能防止sql非法注入

第四种:select * from student where sanme like "%"#{v}"%",可以模糊查询也可以防止注入

第五种:<bind name="aa" value="_parameter+'%'"/>
                 select * from student where sname like #{aa}  是bind的用法,其中value的意思就是参数加上后模糊的意思,注意不要忘了必须要加的下划线。


 以上就是Mybatis动态 sql中常用的标签。

本篇完
     

猜你喜欢

转载自blog.csdn.net/m0_48011056/article/details/126337066
今日推荐