使用tk mybatis 批量增删改查
时间: 2023-09-24 16:14:09 浏览: 95
可以通过使用 MyBatis 的 `batch` 操作来实现批量增删改查。
首先,需要在 Mapper 中定义对应的方法,如下所示:
```java
public interface UserMapper {
void insertUsers(@Param("users") List<User> users);
void updateUsers(@Param("users") List<User> users);
void deleteUsers(@Param("ids") List<Integer> ids);
List<User> selectUsers(@Param("ids") List<Integer> ids);
}
```
然后,在 Mapper.xml 文件中实现对应的 SQL 语句,如下所示:
```xml
<insert id="insertUsers" parameterType="java.util.List">
insert into user (id, name, age) values
<foreach collection="users" item="user" separator=",">
(#{user.id}, #{user.name}, #{user.age})
</foreach>
</insert>
<update id="updateUsers" parameterType="java.util.List">
<foreach collection="users" item="user" separator=";">
update user set name=#{user.name}, age=#{user.age} where id=#{user.id}
</foreach>
</update>
<delete id="deleteUsers" parameterType="java.util.List">
delete from user where id in
<foreach collection="ids" item="id" separator="," open="(" close=")">
#{id}
</foreach>
</delete>
<select id="selectUsers" parameterType="java.util.List" resultMap="userResultMap">
select * from user where id in
<foreach collection="ids" item="id" separator="," open="(" close=")">
#{id}
</foreach>
</select>
```
接下来,在 Java 代码中调用对应的方法,如下所示:
```java
SqlSession sqlSession = sqlSessionFactory.openSession();
try {
UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
// 批量插入用户
List<User> users = new ArrayList<>();
users.add(new User(1, "张三", 20));
users.add(new User(2, "李四", 21));
users.add(new User(3, "王五", 22));
userMapper.insertUsers(users);
// 批量更新用户
users = new ArrayList<>();
users.add(new User(1, "张三三", 23));
users.add(new User(2, "李四四", 24));
users.add(new User(3, "王五五", 25));
userMapper.updateUsers(users);
// 批量删除用户
List<Integer> ids = new ArrayList<>();
ids.add(1);
ids.add(2);
ids.add(3);
userMapper.deleteUsers(ids);
// 批量查询用户
ids = new ArrayList<>();
ids.add(1);
ids.add(2);
List<User> userList = userMapper.selectUsers(ids);
} finally {
sqlSession.close();
}
```
以上就是使用 MyBatis 的 `batch` 操作实现批量增删改查的方法。
阅读全文