XML 中书写sql (动态SQL )
1.#{}与${}
#{}表⽰⼀个,使⽤占位符可以防⽌sql注⼊,
$ {}通过${}可以将parameterType传⼊的内容拼接在中,不能防⽌sql注⼊,但是有时⽅便
例:
再⽐如order by排序,如果将列名通过传⼊sql,根据传的列名进⾏排序,应该写为:
如果使⽤#{}将⽆法实现此功能。sql中update什么意思
2.传递包装类型
3.动态sql
可以对输出参数进⾏判断,若果输⼊参数不为空,或是符合条件才进⾏sql拼接(where ⼦句能够⾃动消除第⼀个and-)
4.foreach
使⽤foreach循环遍历 collection:指定集合的输⼊对象 item:每个遍历⽣成的对象 open:开始遍历时⽣成 close:结束遍历时⽣成separator:遍历两个对象中间的拼
SELECT  * FROM  USER  WHERE  username LIKE  '%${name}%'
1ORDER  BY  ${columnName}
1public  class  UserVo {    private  Administration adm ;      //⾃定义⽤户扩展类    private  UserCustom userCustom ;}
1
2
3
4
5<select  id ="findUserList" parameterType ="userVo" resultType ="UserCustom">          SELECT  * FROM  adm where  adm .sex =          #{userCustom.sex} and adm.username LIKE '%${userCustom.username}%'</select >
1
2
3
4<sql  id ="search">        t .del_flag = #{DEL_FLAG_NORMAL}  <if  test ="sqlMap.search != null and sqlMap.search != ''">    and  (t .value  like  CONCAT ('%',#{sqlMap.search},'%') or t.property like CONCAT('%',#{sqlMap.search},'%')arks like CONCAT('%',#{sqlMap.search
</if ></sql ><select  id ="countAll" resultType ="int">    select          count (*)    from  tag t      <where >        <include refid ="search" />    </where ></select >1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
再例
5.更新语句中if ,和set
在这⾥,会根据标签中内容的有⽆来确定要不要加上set,同时能⾃动过来内容后缀逗号,但是有⼀点要注意,不同于,当中内容为空时,我们可以查出所有⼈的信息,但是这⾥更新语句中,内容为空时,语句变成update person
6.选择choose
<update  id ="delete">    update  tag set        update_date =now (),        del_flag =#{delFlag}    where  id in    <foreach collection ="ids" item ="id" open ="(" close =")" separator =",">      #{id}  </foreach ></update >1
2
3
4
5
6
7
8
9
SELECT  * FROM  USER  WHERE  id =1 OR  id =10 OR  id =16
1<where >    <if  test ="ids != null">      <foreach collection ="ids" item ="user_id" open ="And ( " close =")" separator ="OR">        <!-- 每个遍历中所需拼接的字符串 -->          id =#{user_id}    </foreach >    </if ></where >
1
2
3
4
5
6
7
8<update  id ="updatePerson1">    update  person    <set >     <if  test ="name != null">            NAME = #{name},        </if >        <if  test ="gender != null">            GENDER = #{gender},        </if >    </set ></update >
1
2
3
4
5
6
7
8
9
10
11<choose >  <when  test ="null != sort and '' != sort">      order  by  ${sort}  </when >  <otherwise >      order  by  id desc    </otherwise ></choose >1
2
3
4
5
6
7
8