spring boot mybatis 批量添加sql
时间: 2023-09-09 17:09:51 浏览: 115
Mybatis数据批量插入如何实现
使用MyBatis的批量插入功能可以大大提高数据插入的效率,具体操作如下:
1.在Mapper.xml文件中添加批量插入的SQL语句,例如:
```xml
<insert id="batchInsert" parameterType="java.util.List">
insert into user (name, age, gender) values
<foreach collection="list" item="item" index="index" separator=",">
(#{item.name}, #{item.age}, #{item.gender})
</foreach>
</insert>
```
2.在Java代码中调用批量插入的方法,例如:
```java
@Autowired
private UserMapper userMapper;
public void batchInsert(List<User> userList) {
userMapper.batchInsert(userList);
}
```
3.在调用批量插入方法时,将需要插入的数据封装为List集合,例如:
```java
List<User> userList = new ArrayList<>();
User user1 = new User("Tom", 18, "male");
User user2 = new User("Jack", 20, "male");
userList.add(user1);
userList.add(user2);
batchInsert(userList);
```
阅读全文