第一種(用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