Mybatis使用系列
Mybatis批量插入
方法一
// Dao层
int batchInsert(List<User> users);
//Mapper层
<insert id="batchInsert">
insert into user (id, name, gender) values
<foreach collection="list" item="po" separator=",">
(#{po.id},#{po.name},#{po.gender})
</foreach>
</insert>
这种方法可以批量插入list, 前提是id, name ,gender
每个字段都有值,且不为null, 如果有null就抛错
方法二
int batchInsert(List users);
//Mapper层
<insert id="batchInsert">
<foreach collection="list" item="po" separator="union all">
insert into user
<trim prefix="(" suffix=")" suffixOverrides=",">
<if test="po.id != null">
id,
</if>
<if test="po.name != null">
name,
</if>
<if test="po.gender != null">
gender,
</if>
</trim>
<trim prefix="values (" suffix=")" suffixOverrides=",">
<if test="po.id != null">
#{po.id},
</if>
<if test="po.name != null">
#{po.name},
</if>
<if test="po.gender != null">
#{po.gender},
</if>
</trim>
</foreach>
</insert>
这种方法可以批量插入list, 不再需要每一个值都非null