解決Mybatis中foreach嵌套使用if標簽對象取值的問題
foreach嵌套使用if標簽對象取值問題
最近做項目過程中,涉及到需要在 Mybatis 中 使用 foreach 進行循環(huán)讀取傳入的查詢條件,動態(tài)拼接SQL語句,接口傳入的查詢條件格式:{"advanceSearchList":[{"searchType":10,"searchText":"12"}]} ,根據(jù)我定義的參數(shù)格式,需要在 Mybatis中動態(tài)去循環(huán)讀取 advanceSearchList 集合中的json對象,并根據(jù) json對象中的 searchType 做不同的處理,需要在 foreach 中嵌套 if 標簽進行判斷使用。
大體格式
? ? ? ? <foreach collection="advanceSearchList" item="item" index="index" > ? ? ? ? ? ? <if test="xxx == 10 "> ? ? ? ? ? ? ? ? and abc like CONCAT('%', ddd, '%') ? ? ? ? ? ? </if> ? ? ? ? </foreach>
因為當前 foreach 中獲取到的 item 是一個json對象,涉及到在 if 標簽中獲取當前對象中指定屬性的值,一時腦抽,沒有想起來取值辦法,咨詢?nèi)f能的度娘沒有得到滿意的回復(fù),經(jīng)過自己傻瓜式的嘗試,終于找到了取值方法,特此記錄下:
解決辦法
Mybatis 在 foreach 標簽中使用 if 標簽獲取對象屬性方法:
直接通過 對象.屬性 的方式獲?。。。?!對,你沒看錯,就是直接通過 對象.屬性 的方式獲取?。?!
例如:當前foreach 循環(huán)獲取的對象是 item,想要獲取對象中的 searchType ,直接就是 item.searchType 即可……
代碼如下
? ? ? ? <foreach collection="advanceSearchList" item="item" index="index" > ? ? ? ? ? ? <if test="item.searchType == 10 "> ? ? ? ? ? ? ? ? and abc like CONCAT('%', #{item.searchText}, '%') ? ? ? ? ? ? </if> ? ? ? ? </foreach>
Mybatis if 語句嵌套
在使用mybatis的時候,可以在 if 標簽下面加上if標簽。
比如要對這個sql語句進行改進。
select a.* from emp a? inner join dept b on a.deptno = b.no where ?b.place= #{place}
要求
如果 傳入的 地點 是 North Korea 那么 符合 a中的條件也可以。
a.male = 'M' or a.age ?bewteen ?20 and 30?
where語句可以這么寫
select * from emp e? <where> <if test="_parameter.place != null and _parameter.place != '' "> and? <if test="_parameter.place == 'North Korea' "> ?( ?</if> b.place = #{place} <if test="_parameter.place == 'North Korea' "> or a.male = 'M' or a.ge between 20 and 30 ?) </if> </if> </where>
注意里面的括號。
以上為個人經(jīng)驗,希望能給大家一個參考,也希望大家多多支持腳本之家。
相關(guān)文章
java 漢諾塔Hanoi遞歸、非遞歸(仿系統(tǒng)遞歸)和非遞歸規(guī)律 實現(xiàn)代碼
漢諾塔(Hanoi) 算法Java實現(xiàn)。通過三個函數(shù),分別對Hanoi進行遞歸、非遞歸和非遞歸規(guī)律實現(xiàn)。2013-05-05使用Eclipse創(chuàng)建Maven的Java WEB項目的兩種方式
本文詳細介紹了如何在JDK 1.8、Maven 3.6.3和Eclipse 2017版本下創(chuàng)建Java Web項目,包括選擇archetype方式、配置Tomcat、設(shè)置為Web3.1、配置Maven編譯級別、修復(fù)Eclipse提示的錯誤、設(shè)置Maven源文件夾等步驟,需要的朋友可以參考下2024-11-11