实现动态删除多个数据,这里我们需要用到 foreach 标签,这个标签还可以运用到批量插入,反正需要对集合进行遍历时就可以使用该标签,标签有如下属性 :
新建了一个 userInfo2Mapper 接口,然后写下如下代码,声明 batchDelete 方法
package com.example.mybatisdemo.mapper;
import com.example.mybatisdemo.model.UserInfo;
import org.apache.ibatis.annotations.*;
import java.util.List;@Mapper
public interface UserInfo2Mapper {Integer batchDelete(@Param("ids")List<Integer> ids);
}
在resources 中创建 Userinfo2XMLMapper.xml 文件
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN""http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.example.mybatisdemo.mapper.UserInfo2Mapper"><delete id="batchDelete">delete from userinfowhere id in<foreach collection="ids" separator="," item="id" open="(" close=")">#{id}</foreach></delete>
</mapper>
再回到接口,然后Generate,test,勾选 batchDelete,ok,然后补充代码
package com.example.mybatisdemo.mapper;import com.example.mybatisdemo.model.UserInfo;
import lombok.extern.slf4j.Slf4j;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;import java.lang.reflect.Array;
import java.util.Arrays;
import java.util.List;import static org.junit.jupiter.api.Assertions.*;@Slf4j
@SpringBootTest
class UserInfo2MapperTest {@Autowiredprivate UserInfo2Mapper userInfo2Mapper;@Testvoid batchDelete() {userInfo2Mapper.batchDelete(Arrays.asList(11,12,13,14));}
}
再打开数据库查看,没毛病,11~14的数据都删了