第一種(用Mapper.xml映射文件中定義了操作數據庫sql)
注意點:
1.#{}與${}
#{}表示一個占位符,使用占位符可以防止sql注入,
${}通過${}可以將parameterType傳入的內容拼接在sql中,不能防止sql注入,但是有時方便
例
SELECT * FROM USER WHERE username LIKE '%${value}%'
再比如order by排序,如果將列名通過參數傳入sql,根據傳的列名進行排序,應該寫為:
ORDER BY${columnName}
如果使用#{}將無法實現此功能。
2.傳遞包裝類型
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:遍歷兩個對象中間的拼
-->
在例
SELECT * FROM USER WHERE id=1 OR id=10 ORid=16
<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