Mybatis批量插入的使用

来源:互联网 发布:洛阳网站建设启辰网络 编辑:程序博客网 时间:2024/06/01 12:36

mybatis批量插入数据

由于项目需要生成多条数据,考虑到循环插入需要执行多条sql语句,并且在程序意外终止的情况下,用户不能直接的了解到我们成功插入多数据影响后续的操作,这是存在的一个潜在的bug。所以在程序中封装了一个List集合对象,然后需要把该集合中的实体插入到数据库中,使用MyBatis批量插入,由于之前没用过批量插入,在网上找了一些资料后最终实现了,把详细过程记录下来。供以后查阅和学习。

(以项目中的某一模块作为例子)首先我们在java代码中遍历插入数据,然后再将其添加到List对象集合中去,再调用我们的batchInsert()批量插入的方法

 List<TemporaryStudent> srList =  Lists.newArrayList();            for(Student student : studentList){                temporaryStudent.setName(student.getName());                temporaryStudent.setNumber(student.getNumber());                temporaryStudent.setCreated(DateUtils.getSecondTimestampTwo(startDate));                temporaryStudent.setEndTime(DateUtils.getSecondTimestampTwo(endDate));                temporaryStudent.setStatus(1);                tsList.add(temporaryStudent);            }            temporaryStudentService.batchInsert(tsList);

-调用的方法:

/**     * 批量插入     * @param list     */    void batchInsert(List<TemporaryStudent> list);

接下来是我们Mapper.xml文件中的具体的sql语句

<!--批量插入-->    <insert id="batchInsert" parameterType="java.util.List">        INSERT INTO ex_temporary_student        <trim prefix="(" suffix=")" suffixOverrides=",">                name,                number,                created,                end_time,                status        </trim>        VALUES        <foreach collection="list" item="item" index="index" separator="," >            (                #{item.name},                #{item.number},                #{item.created},                #{item.endTime},                #{item.status}            )        </foreach>    </insert>

执行的打印结果:

insert into ex_temporary_student (name, number, created, end_time,status) values (?,?,?,?,? ),(?,?,?,?,? ),(?,?,?,?,? ),(?,?,?,?,? )...

最重要的一个就是forEach循环:

它可以在SQL语句中进行迭代一个集合。

  • foreach元素的属性主要有 item,index,collection,open,separator,close。
  • item表示集合中每一个元素进行迭代时的别名,index指定一个名字,用于表示在迭代过程中,每次迭代到的位置,open表示该语句以什么开始,separator表示在每次进行迭代之间以什么符号作为分隔 符,close表示以什么结束,在使用foreach的时候最关键的也是最容易出错的就是collection属性,该属性是必须指定的,但是在不同情况 下,该属性的值是不一样的,主要有一下3种情况:

    1. 如果传入的参数是多个的时候,我们就需要把它们封装成一个Map了。
    2. 如果传入的是单参数且参数类型是一个array数组的时候,collection的属性值为array
    3. 如果传入的是单参数且参数类型是一个List的时候,collection属性值为list

在这里涉及到的trim标签属性:
- prefix:前缀覆盖并增加其内容
- suffix:后缀覆盖并增加其内容
- prefixOverrides:前缀判断的条件
- suffixOverrides:后缀判断的条件

原创粉丝点击