第一种(用Mapper.xml映射文件中定义了操做数据库sql)sql
注意点:数据库
1.#{}与${}app
#{}表示一个占位符,使用占位符能够防止sql注入,spa
${}经过${}能够将parameterType传入的内容拼接在sql中,不能防止sql注入,可是有时方便code
例xml
SELECT * FROM USER WHERE username LIKE '%${value}%'
再好比order by排序,若是将列名经过参数传入sql,根据传的列名进行排序,应该写为:对象
ORDER BY${columnName}blog
若是使用#{}将没法实现此功能。排序
2.传递包装类型rem
public class QueryVo { private User user; //自定义用户扩展类 private UserCustom userCustom;
<select id="findUserList" parameterType="queryVo" resultType="UserCustom">
SELECT * FROM USER where user.sex=#{userCustom.sex} and user.username LIKE '%${userCustom.username}%'
</select>
3.动态sql
能够对输出参数进行判断,若果输入参数不为空,或是符合条件才进行sql拼接(<!-- where 子句可以自动消除第一个and -->)
<select id="countAll" resultType="int"> select count(*) from tag t <where> <include refid="search" /> </where> </select>
<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},'%')or t.remarks like CONCAT('%',#{sqlMap.search},'%')) </if> </sql>
4.foreach
<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>
<!--
使用foreach循环遍历
collection:指定集合的输入对象
item:每一个遍历生成的对象
open:开始遍历时生成
close:结束遍历时生成
separator:遍历两个对象中间的拼
-->
在例
<where> <if test="ids != null"> <foreach collection="ids" item="user_id" open="And ( " close=")" separator="OR"> <!-- 每一个遍历中所需拼接的字符串 --> id=#{user_id} </foreach> </if> </where>
5.更新语句中if,和set
<update id="updatePerson1"> update person <set> <if test="name != null"> NAME = #{name}, </if> <if test="gender != null"> GENDER = #{gender}, </if> </set> </update>
在这里,<set>会根据标签中内容的有无来肯定要不要加上set,同时能自动过来内容后缀逗号,可是有一点要注意,不一样于<where>,当<where>中内容为空时,咱们能够查出全部人的信息,可是这里更新语句中,<set>内容为空时,语句变成update person