目录
一、前言
数据库批量处理能够大幅度提高程序运行效率,减小数据库访问压力的有效方法之一。为了实现数据库能够批量处理数据,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属性到底是要什么值,你也就知道了。
最后,感谢大家的观看!