<insert id="insertBatch">
inset into users(username,brithday,sex,address) values
<foreach collection="list" item="user" separator=",">
</foreach>
</insert>
foreah标签主要是用来进行集合或数组的遍历主要有以下的参数:
collection:属性的值为 list array map 就是参数位置传过来的类型三种分别对应的参数是List 数组 map集合
应用场景:查询多个指定id的用户信息
接口:
List<User>getByIds(Integer arr[]);
在编写mapper文件的时候当入参是数组集合map,参数超过一个时候参数parameterType省略
mapper.xml: 就是吧数组中传过来的参数进行一个遍历 加入数组的内容是1,2,3那么查询的内容就是id 是1,2,3的数据
item是每次遍历出来的对象或者值 名字可以任意
separator是多个值或对象之间的分隔符
open是整循环的前括号
close是整个循环的后括号
<select id="getByIds" resultType="users">
select * from users where id in(
<foreach collection="array" item="item" separator="," open="(" close=")">
#{id}
</foreach>
)
</select>
案例:批量删除
int deleteBatch(Integer arr[]);
mapper.xml
<delete id="deleteBarch">
delete from users where id in
<foreach collecton="array" separator="," open="(" close=")" item="id">
@{id}
</foreach>
</delete>
批量增加 注意这个不需要加前后括号因为插入值每插入一个值都是一个括号括号是在里面的同时使用逗号进行分隔只要了解sql语句理解
int insertBatch(List<Users> list);
mapper.xml
<insert id="insertBatch">
insert into users values
<foreach collection="list" item="user" separator=",">
(#{user.username},#{user.password},#{user.sex},#{user.address})
</foreach>
</insert>
批量更新
注意:如果想要使用批量更新必须在链接数据库的配置文件中url中添加&allowMultiQueries=true允许多行操作才可以执行
<!-- separator=";"用分号隔开是因为每一条更新语句都是独立的 -->
<update id="updateSet">
<foreach collection="list" item="user" separator=";">
update users
<set>
<if test="user.username!=null and user.username!=''">
username=#{user.username}
</if>
<if test="user.password!=null and user.password!=''">
password=#{user.password}
</if>
</set>
where id=#{user.id}
</foreach>
</update>