動態SQLjava
通常的狀況我就再也不贅述了,官方文檔上都有,此處我就寫幾個個案吧.dom
Like模糊查詢:ide
有三種狀況:spa
(1) '%'||#{username}||'%'blog
(2) #{username} 在java代碼中寫入userDao.queryUserByName("%2%");文檔
(3) <select id="queryUserByName" parameterType="String" resultType="User">it
<bind name="pattern" value="'%' + _parameter + '%'" />io
SELECT * FROM test_usertest
WHERE title LIKE #{pattern}email
</select>
注:此處的_parameter 是指傳入的String類型參數
Where條件加if判斷:
<trim prefix="WHERE" prefixOverrides="AND |OR ">
<if test="_parameter !=null">
and username like '%'||#{username}||'%'
</if>
</trim>
或
<where>
<if test="_parameter !=null">
and username like '%'||#{username}||'%'
</if>
</where>
動態更新語句類似的解決方案是 set
<update id="updateAuthorIfNecessary"
parameterType="domain.blog.Author">
update Author
<set>
<if test="username != null">username=#{username},</if>
<if test="password != null">password=#{password},</if>
<if test="email != null">email=#{email},</if>
<if test="bio != null">bio=#{bio}</if>
</set>
where id=#{id}</update>