MyBatis是一个持久层框架,它可以帮助我们快速实现对数据库的操作。MyBatis支持三种方式的批量插入数据,分别是:
1. 使用foreach标签
使用foreach标签可以将一个集合中的数据进行批量插入,例如:
insert into user(name, age) values (#{item.name}, #{item.age})
2. 使用useGeneratedKeys和selectKey标签
使用useGeneratedKeys和selectKey标签可以实现自动生成主键,例如:
insert into user(name, age) values (#{item.name}, #{item.age}) select last_insert_id()
3. 使用BatchExecutor
使用BatchExecutor可以将多条SQL语句放到一个批处理中,实现批量插入,例如:
select last_insert_id() insert into user(id, name, age) values(#{item.id}, #{item.name}, #{item.age})
上述三种方式都可以实现批量插入数据,用户可以根据自己的需求选择合适的方式。