背景:在代码中循环插入和在数据库中循环插入,速度真的差好多。之前和同事测试了一下,10个数据在两种情况下,速度差的不是一点点。
<foreach collection="集合名或者数组名" item="元素" separator="标签分隔符" open="以什么开始" close="以什么结束">
#{元素}
</foreach>
collection:接收的集合或者数组,集合名或者数组名
item属性: 集合或者数组参数中的每一个元素
1.批量增加
<insert id="savequestion" >
insert into t_exam_question (exam_id,question_id) value
<foreach collection="ids" item="id" index="index" separator=",">
(#{examId},#{id})
</foreach>
</insert>
2.批量删除
<delete id="delClass">
DELETE FROM t_class WHERE id IN
<foreach collection="ids" item="id" separator="," open="(" close=")">
#{id}
</foreach>
</delete>
3批量查找
<select id="findClassUser" resultType="int">
SELECT user_id from t_class_user where class_id IN
<foreach collection="ids" item="id" separator="," open="(" close=")">
#{id}
</foreach>
</select>
4.批量修改
<update id="updateUser" >
<foreach collection="list" item="user" separator=";">
update t_user
<set>
username=#{user.username}
</set>
where id=#{user.id}
</foreach>
</update >
当然在这边,批量修改相当于很多句update句子,在mybatis中是默认不能多条语句一起。所以在连接数据库的url中添加一个属性。
&allowMultiQueries=true
可以了,下次可以直接看了 方便学习