利用 <foreach> 标签可以遍历迭代集合、数组元素,批量的执行增删命令。
package com.atguigu.mybatis.mapper;
import org.apache.ibatis.annotations.Param;
public interface DynamicSQLMapper {
int deleteMoreByArray(@Param("eids") Integer[] eids);
}
-mapper.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.atguigu.mybatis.mapper.DynamicSQLMapper">
<delete id="deleteMoreByArray">
delete from users where id in
<foreach collection="eids" item="eid" separator="," open="(" close=")">
#{eid}
</foreach>
</delete>
</mapper>
package com.atguigu.mybatis.test;
import com.atguigu.mybatis.mapper.DynamicSQLMapper;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.junit.Test;
import java.io.IOException;
import java.io.InputStream;
public class DynamicSQLMapperTest {
@Test
public void testDeleMoreByArray() throws IOException {
InputStream is = Resources.getResourceAsStream("mybatis-config.xml");
SqlSessionFactoryBuilder sqlSessionFactoryBuilder = new SqlSessionFactoryBuilder();
SqlSessionFactory sqlSessionFactory= sqlSessionFactoryBuilder.build(is);
SqlSession sqlSession = sqlSessionFactory.openSession(true);
DynamicSQLMapper mapper = sqlSession.getMapper(DynamicSQLMapper.class);
int result = mapper.deleteMoreByArray(new Integer[]{6,7,8});
System.out.println(result);
}
}
- 原先数据库一共7条数据
删除之后剩下5条数据
|