1、批量更新
mapper 接口:批量方法插入
void batchInsert(@Param("users") List<User> users)
mapper xml: 批量插入xml
<insert id="batchInsert" paramterType="java.util.List">
insert into biz_user (id, name, sex) values
<foreach collection="users" item="item" index="index" separator=",">
(#{item.id},#{item.name},#{item.sex})
</foreach>
</insert>
2、批量插入
mapper 接口:批量方法插入
void batchUpdate(@Param("users") List<User> users)
mapper xml: 批量更新xml (通过拼接SQL语句)
<!-- 通过接收传进来的参数list进行循环着组装sql -->
<update id="batchUpdate" parameterType="java.util.List">
<!-- 接收list参数,循环着组装sql语句;注意for循环的写法 separator=";" 代表着每次循环完,在sql后面放一个分号 item="item" 循环List的每条的结果集 collection="users" users即为 map传过来的参数key -->
<foreach collection="users" separator=";" item="item">
update biz_user set
name = #{item.name},
sex = #{item.sex}
where id= #{item.id}
</foreach>
</update>
温馨提示:
在数据库连接配置中必须添加 &allowMultiQueries=true,
jdbc:mysql://127.0.0.1:3306/test?useUnicode=true&characterEncoding=UTF-8&autoReconnect=true&useSSL=false&zeroDateTimeBehavior=convertToNull&allowMultiQueries=true&serverTimezone=Asia/Shanghai
&allowMultiQueries=true 意为 允许批量更新,否则在执行SQL时会报以下异常:
Error updating database. Cause: java.sql.SQLSyntaxErrorException: You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near 'update biz_user set
name = 'zzg',
sex = '1'
报错原因:
是因为spring boot配置文件中,关于数据库的连接配置,并没有允许进行批量更新的操作。
这种方式就是通过SQL拼接,单条单条的进行更新,如果行数多的情况下给不建议使用。
mapper xml: 批量更新xml (通过case when语句)
<update id="batchUpdate" parameterType="java.util.List">
update biz_user
<trim prefix="set" suffixOverrides=",">
<trim prefix="name=case" suffix="end,">
<foreach collection="users" item="item" index="index">
<if test="item.name!= null">
when id= #{item.id} then #{item.name}
</if>
</foreach>
</trim>
<trim prefix="sex=case" suffix="end,">
<foreach collection="users" item="item" index="index">
<if test="item.sex != null">
when id=#{item.id} then #{item.sex}
</if>
</foreach>
</trim>
</trim>
where
<foreach collection="users" separator="or" item="" index="index">
id= #{item.id}
</foreach>
</update>
通过case when语句进行批量更新,只要一条SQL语句.
上面的案列是针对多个字段的情况;如果只是更新单个字段,我们可以这么写:
<update id="batchUpdate" parameterType="java.util.List">
update biz_user
set name = CASE
<foreach collection="users" item="item" index="index">
when id = #{item.id} then #{item.name}
</foreach>
END
WHERE id in
<foreach collection="users" item="item" index="index" open="(" close=")">
#{item.id}
</foreach>
</update>
3、自定义分页
页面请求参数
- 页面显示条数 size
- 第page页面
mapper 接口:分页查询
List<User> page(T t, Integer start, Integer size)
mapper xml: 分页查询
<select id="page" resultMap="BaseResultMap">
select
<include refid="Base_Column_List" />
from biz_user
// start = (page - 1)* size (分页计算)
order by createTime DESC limit #{1},#{2}
</select>