Mybatis常用標籤
阿新 • • 發佈:2021-01-13
mybatis中常用標籤
choose
-
有時候我們並不想應用所有的條件,而只是想從多個選項中選擇一個。而使用if標籤時,只要test中的表示式為 true,就會執行 if 標籤中的條件。MyBatis 提供了 choose 元素。if標籤是與(and)的關係,而 choose 是或(or)的關係。
-
choose標籤是按順序判斷其內部when標籤中的test條件出否成立,如果有一個成立,則 choose 結束。當 choose 中所有 when 的條件都不滿則時,則執行 otherwise 中的sql。類似於Java 的 switch 語句,choose 為 switch,when 為 case,otherwise 則為 default。
-
例如下面例子,同樣把所有可以限制的條件都寫上,方面使用。choose會從上到下選擇一個when標籤的test為true的sql執行。安全考慮,我們使用where將choose包起來,放置關鍵字多於錯誤。
< !-- choose(判斷引數) -引數garbageType 不為空並且為3 屬性作為:where條件 --> < choose> <when test="garbageType != null and garbageType =='3'.toString"> (select b.garbage_type,a.net_weight,b.car_unit_name disposal_site_name,tare_date_time from xs_dispose_weight_${year} a,xs_car b where a.car_code=b.car_code and b.garbage_type=#{garbageType} ) b </when> <otherwise> xs_dispose_weight_${year} b </otherwise> </choose>
- choose (when,otherwize) ,相當於java 語言中的 switch ,與 jstl 中 的 choose 很類似。
< select id="dynamicChooseTest" parameterType="Blog" resultType="Blog"> select * from t_blog where 1 = 1 <choose> <when test="title != null"> and title = #{title} </when> <when test="content != null"> and content = #{content} </when> <otherwise> and owner = "owner1" </otherwise> </choose> </select>
-
when元素表示當 when 中的條件滿足的時候就輸出其中的內容,跟 JAVA 中的 switch 效果差不多的是按照條件的順序,當 when 中有條件滿足的時候,就會跳出 choose,即所有的 when 和 otherwise 條件中,只有一個會輸出,當所有的我很條件都不滿足的時候就輸出 otherwise 中的內容。所以上述語句的意思非常簡單, 當 title!=null 的時候就輸出 and titlte = #{title},不再往下判斷條件,當title為空且 content!=null 的時候就輸出 and content = #{content},當所有條件都不滿足的時候就輸出 otherwise 中的內容。
-
foreach迴圈使用方法
< if test="streetName != null and streetName.size > 0"> and d.streetName IN <foreach close=")" collection="streetName" item="streetName" open="(" separator=","> #{streetName} </foreach> </if>