目錄
一、前言
數據庫批量處理能夠大幅度提高程序運行效率,減小數據庫訪問壓力的有效方法之一。爲了實現數據庫能夠批量處理數據,Mybatis提供相應的標籤<foreach>。
二、<foreach>標籤的介紹
<foreach>標籤一共有六個參數可以設置,分別是:
index:當前的索引(博主理解爲像java裏面for循環一樣,如:for(int i = 0; i < 5; i ++); 類似於這裏的i );
collection:要進行循環的集合 (像你想通過一個列表的id來對數據進行操作的話,那就可以穿進來一個id列表);
open:<foreach>裏面進行拼接的語句是以什麼字符串開始;(不理解的話後面有演示)
separator :循環內容之間是以什麼字符串相隔
close:<foreach>裏面進行拼接的語句是以什麼字符串作爲結束;
item:集合裏面當前下邊索引的對象
下面開始講解如何用<foreach>標籤來對數據進行批量處理。
三、<foreach>標籤的使用
這裏假設我們有一個存儲人物信息的表,代碼中的對象名爲Person
3.1 通過<foreach>實現批量查詢(select)
假設我們要通過幾十個身份證號來查詢出這幾十個人的信息出來,那麼,我們首先將這些身份證號放入一個List集合裏。之後調用批量查詢的接口。
List<Person> queryPersonListByUidList(@Param("uidList") List<String> uidList);
這裏,我們給uidList用@param標籤起了個名字,之後在dao層指定collection集合的時候,就是用這個名字。好了,接口實現如下:
<select id="queryPersonListByUidList" resultMap="BaseResultMap">
select
<include refid="Base_Column_List"/>
from t_person
where uid in
<foreach collection="uidList" item="item" index="index" open="(" separator="," close=")">
#{item}
</foreach>
</select>
其實上面的mybatis語句,換一種方式是這樣子的:
select
<include refid="Base_Column_List"/>
from t_person
where uid in
(uid1,uid2,uid3,uid4,uid5........uidx)
看吧,<foreach>標籤主要的功能是能夠循環賦值。
3.2 通過<foreach>實現批量插入(insert)
一樣的,<foreach>實現批量數據插入,接口定義如下:
int savePersonList(@Param("personList") List<Person> personList);
內部接口實現爲:
<insert id="savePersonList" parameterType="java.util.List">
insert into t_person (uid, name, age, address) values
<foreach collection="personList" item="item" index="index" separator=",">
(#{item.uid,jdbcType=VARCHAR}, #{item.name,jdbcType=VARCHAR},
#{item.age,jdbcType=VARCHAR},#{item.address,jdbcType=VARCHAR})
</foreach>
</insert>
我們這裏可以發現,其實接口的實現還是有些許不同的,就是open和close屬性咱們都沒有設置。
3.3通過<foreach>實現批量更新
接口定義如下:
int updatePersonListByUidList(@Param("personList") List<Person> personList);
內部實現爲:
<update id="updatePersonListByUidList" parameterType="java.util.List">
<foreach collection="personList" item="item" index="index" open="" close="" separator=";">
update t_person
<set>
name=${item.name},
age=${item.age},
address=${item.address}
</set>
where uid = ${item.uid}
</foreach>
</update>
3.4 通過<foreach>進行批量刪除
接口定義爲:
int deletePersonByUidList(@Param("uidList") List<String> uidList);
接口實現爲:
<delete id="deletePersonByUidList" parameterType="java.util.List">
delete from t_person
where uid in
<foreach item="item" index="index" collection="ruleCodeList" open="(" separator="," close=")">
#{item}
</foreach>
</delete>
四、小結
mybatis的<foreach>標籤的實際意義爲,循環拼接mysql批量處理語句,因此只要知道mysql的批量處理語句的格式是怎麼樣的,自己再去寫這個<foreach>語句就會知道它具體爲什麼是這麼寫的,什麼時候要設置open或close屬性,以及separator屬性到底是要什麼值,你也就知道了。
最後,感謝大家的觀看!