天天看點

MyBatis的動态SQL查詢-讓查詢更靈活多變!序言  介紹

序言 

      MyBatis,大家都知道,半自動的ORM架構,原來叫ibatis,後來好像是10年apache軟體基金組織把它托管給了goole code,就重新命名了MyBatis,功能相對以前更強大了。它相對全自動的持久層架構Hibernate,更加靈活,更輕量級,這點我還是深有體會的。

       MyBatis的一個強大特性之一就是動态SQL能力了,能省去我們很多串聯判斷拼接SQL的痛苦,根據項目而定,在一定的場合下使用,能大大減少程式的代碼量和複雜程度,不過還是不是過度太過複雜的使用,以免不利于後期的維護和擴充。

下邊就簡單介紹一下吧。

介紹

foreach 批量處理

<foreach> 元素是非常強大的,它允許你指定一個集合,聲明集合項和索引變量,它們可以用在元素體内。它也允許你指定開放和關閉的字元串,在疊代之間放置分隔符。這個元素是很智能的,它不會偶然地附加多餘的分隔符。注意:你可以傳遞一個 List 執行個體或者數組作為參數對象傳給 MyBatis。當你這麼做的時候,MyBatis 會自動将它包裝在一個Map 中,用名稱在作為鍵。List 執行個體将會以“list”作為鍵,而數組執行個體将會以“array”作為鍵。最常用在批量删除和批量插入功能上,如下:

<!-- 批量删除資料 -->
	<delete id="batchDelete">
	  	delete from test where id in
	  	<foreach collection="list" index="index" item="item" open="(" separator="," close=")">
	  	 	#{item}
	  	</foreach>
	</delete>
           
<!--批量插入資料-->
	<insert id="batchInsert">
		insert into test (id, name, year,birthday) values
		<foreach collection="list" item="item" index="index" separator=",">
			(#{id}, #{name},#{year},#{birthday,jdbcType=DATE})
		</foreach>
	</insert>
           

if經常判空使用

<!--更新資料,根據傳入條件選擇性更新資料,如id為null,則更新全部資料-->
	<update id="update" parameterType="com.inspur.demo.po.ExampleBean" >
	    update test set name=#{name},year=to_number(#{year}),birthday=to_date(#{birthday},'yyyy-mm-dd hh24:mi:ss')
	    <if test="id!=null">
	    	where id = #{id}
	    </if>
	</update>
           

where set的使用

       <where> 元素知道如果由被包含的标記傳回任意内容,就僅僅插入“WHERE” 。而且,如果以“AND”或“OR”開頭的内容,那麼就會跳過 WHERE 不插入。

<where>
			<if test="id!= null">
				m.id=#{id}
			</if>
			<if test="name!= null">
				and m.name like '%${name}%'
			</if>
			<if test="year!= null">
				and m.year=#{year,jdbcType=INTEGER}
			</if>
			<if test="birthday!= null">
				<![CDATA[and to_char(m.birthday,'yyyy-MM-dd') < #{birthday}]]>
			</if>
		</where>
           

       <set> 元素可以被用于動态包含更新的列,而不包含不需更新的。

<!--更新資料,根據傳入條件選擇性更新資料,如id為null,則更新全部資料-->
	<update id="update" parameterType="com.inspur.demo.po.ExampleBean" >
	    update test
	    	<set>
			<if test="name!= null">name=#{name},</if>
			<if test="year!= null">year=#{year,jdbcType=INTEGER},</if>
			<if test="birthday!= null">birthday=#{birthday,jdbcType=DATE}</if>
		</set>
		<if test="id=!null" >
			where id=#{id}
		</if>
	</update>
           

choose when的使用(相對來說用的少)

<!-- 一些情況可選擇choose,when,otherwise的使用 -->
	<select id="getByBean" parameterType="com.inspur.demo.po.ExampleBean" resultType="map">
		select m.* from test m where 1=1
		<choose>
			<when test="判斷1">
				and 條件1
			</when>
			<when test="判斷2">
				and 條件2
			</when>
			<otherwise>
				and 條件3
			</otherwise>
		</choose>
	</select>
           

轉載請注明—作者:Java我人生(陳磊興)   原文出處:http://blog.csdn.net/chenleixing/article/details/43818227

繼續閱讀