批处理
xml方式
批处理方式无法执行回写操作
<insert id="batchInsert" parameterType="java.util.List">
insert into students(stu_name,stu_sex) values
<foreach collection="list" item="item" index="index" separator=",">
<!--cillection="list" 是MyBatis的强制要求,代表当前要遍历的集合-->
<!--item属性指定当前迭代变量,index属性指定当前迭代索引-->
<!--separator属性指定分隔符,MySQL插入多条数据时就是使用逗号进行分隔的所以指定逗号-->
(#{item.stuName},#{item.stuSex})
</foreach>
</insert>
<delete id="batchDelete" parameterType="java.util.List">
delete from students where stu_id in
<foreach collection="list" item="item" index="index" separator="," open="(" close=")"> <!--删除也是同理-->
<!--open和close属性用于动态生成括号-->
#{item}
</foreach>
</delete>
用于测试关键代码片段,在创建sqlSession
对象时需要将自动事务提交关闭,并手动提交和回滚,其他代码省略
/*批量新增*/
List<Student> students = new ArrayList<>();
for (int i = 0; i < 10; i++) {
Student student = new Student();
student.setStuName("张三" + i);
students.add(student);
}
int number = sqlSession.insert("student.batchInsert", students);
sqlSession.commit(); //手动提交
System.out.println(number); //查看影响条数
/*批量删除*/
List<Integer> stuIds = new ArrayList<>();
for (int i = 0; i < 10; i++) {
stuIds.add(i);
}
number = sqlSession.delete("student.batchDelete", stuIds);
sqlSession.commit(); //手动提交
System.out.println(number); //查看影响条数
注解方式
package com;
import org.apache.ibatis.annotations.Delete;
import org.apache.ibatis.annotations.Insert;
import java.util.List;
public interface StudentMapper {
@Insert(
"<script>" + //使用script标签即可像xml中一样书写
"insert into students(stu_name,stu_sex) values" +
"<foreach collection='list' item='item' index='index' separator=','>" +
"(#{item.stuName},#{item.stuSex})" +
"</foreach>" +
"</script>"
)
int batchInsert(List<Student> students);
@Delete(
"<script>" + //使用script标签即可像xml中一样书写
"delete from students where stu_id in" +
"<foreach collection='list' item='item' index='index' separator=',' open='(' close=')'>" +
"#{item}" +
"</foreach>" +
"</script>"
)
int batchDelete(List<Integer> stuIDs);
}
用于测试关键代码片段,在创建sqlSession
对象时需要将自动事务提交关闭,并手动提交和回滚,其他代码省略
StudentMapper studentMapper = sqlSession.getMapper(StudentMapper.class);
/*批量新增*/
List<Student> students = new ArrayList<>();
for (int i = 0; i < 10; i++) {
Student student = new Student();
student.setStuName("张三" + i);
students.add(student);
}
int number = studentMapper.batchInsert(students);
sqlSession.commit(); //手动提交
System.out.println(number); //查看影响条数
/*批量删除*/
List<Integer> stuIds = new ArrayList<>();
for (int i = 0; i < 10; i++) {
stuIds.add(i);
}
number = studentMapper.batchDelete(stuIds);
sqlSession.commit(); //手动提交
System.out.println(number); //查看影响条数
Comments NOTHING