mybatis的動態(tài)sql之if test的使用說明
<select parameterType='java.lang.String' resultType='java.lang.String'> SELECT MAX(DEPART_ID) FROM T_P_DEPART <where> <if test='_parameter!=null and _parameter!=’’'> AND DEPART_PID = #{departId,jdbcType=VARCHAR} </if> <if test='_parameter==null or _parameter==’’'> AND DEPART_PID IS NULL </if> </where> </select>參數(shù)為pojo , if test讀取該參數(shù)代碼
<select parameterType='ShopVo' resultType='ShopCustomer'> select * from shop <where> <if test='shopCustomer.shopname!=null and shopCustomer.shopname!=’’'>shop.shopname like ’%${shopCustomer.shopname}%’ </if> <if test='shopCustomer.shopname==null or shopCustomer.shopname==’’'> AND shop.shopname is null </if> </where></select>
補充:關(guān)于mybatis中 if test的條件怎么寫
1.mybatis 中 的 if test寫法1.1官方文檔上對于if是這么寫的<if test='title != null'> AND title like #{title}</if>
參考官方文檔:
實際項目中會有這種情況: 頁面上title字段輸入某個值進(jìn)行查詢,手動將輸入框中的值刪除,然后再次查詢,發(fā)現(xiàn)結(jié)果不正確,究其原因是應(yīng)為title傳入了空串' ' 這樣在mybatis配置文件中就會用空串進(jìn)行查詢,導(dǎo)致出現(xiàn)錯誤結(jié)果
1.2建議寫法<if test='title != null and title != ’’' > AND title like #{title}</if>2.使用mybatis 做修改時將字段置空
if中如果傳入的參數(shù)如果為空,那么將不會執(zhí)行if中的語句
解決辦法:<update parameterType='*.*.Object' >update table <set> <if test='Object.fullName == null or Object.fullName ==’’'> full_name = null, </if> <if test='Object.fullName != null and Object.fullName !=’’'> full_name = #{companyOrg.fullName}, </if> <if test='Object.level == null or Object.level ==’’'> level = null, </if> <if test='Object.level == 0 '> level = null, </if> <if test='Object.level != null and Object.level !=’’ and Object.level != 0 '> level = #{companyOrg.level}, </if> </set> where 1=1 and id =#{companyOrg.id}</update>
以上為個人經(jīng)驗,希望能給大家一個參考,也希望大家多多支持好吧啦網(wǎng)。如有錯誤或未考慮完全的地方,望不吝賜教。
相關(guān)文章:
1. Linux安裝MariaDB數(shù)據(jù)庫的實例詳解2. CentOS 7中成功安裝MariaDB的方法教程3. centos中找回MariaDB數(shù)據(jù)庫root用戶權(quán)限的方法4. MariaDB數(shù)據(jù)庫的外鍵約束實例詳解5. mariadb 在低配 VPS 上崩潰問題處理方案6. SQLite字符串比較時的大小寫問題解決方法7. 我是如何用2個Unix命令給MariaDB SQL提速的8. MongoDB啟動報錯 28663 Cannot start server9. Windows10系統(tǒng)下安裝MariaDB 的教程圖解10. SQLite教程(十):內(nèi)存數(shù)據(jù)庫和臨時數(shù)據(jù)庫
