mybatis plus-批量操作

时间:2025-03-20 13:11:57

方法1:
使用mybatis plus内置的方法。目前常用的就一下几个方法。

// 插入(批量)
boolean saveBatch(Collection<T> entityList);
// 插入(批量)
boolean saveBatch(Collection<T> entityList, int batchSize);

// 删除(根据ID 批量删除)
boolean removeByIds(Collection<? extends Serializable> idList);

方法2:
使用xml编写sql文件进行批量查询。注意:foreach的使用

//批量添加
//java
public Integer batchAdd(List<User> user)
<insert id="batchAdd" >
insert into user(u_name,u_age) values
<foreach collection ="list" item="item" separator = ",">
	(#{},#{})
</foreach>
</insert>

注意:collection和item永远是必填项。
collection:
(1)只有一个参数的情况 List对象,则collection=“list”即可。
(2)只有一个参数的情况Array对象,则collection=“array” 即可。
(3)还有一种特殊情况。如下输入参数。如果想要遍历ids。那么此时指定collection=“ids”即可。

class User{
	private String name;
	private String[] ids;
}

(4)多个参数,最好使用Param指定每个参数的别名。
让collection=“别名”(或者是map类型的输入参数,collection=“对应的key”)