MyBatis如何实现数据的批量新增和删除呢?
下文笔者讲述Mybatis中批量删除和批量新增的操作方法分享,如下所示
批量删除和批量新增的实现思路
使用 foreach关键字 即可生成批量删除脚本例:Mybatis创建批量删除和批量新增的操作示例
创建UserMapper接口 (用户信息Mapper动态代理接口) 实现用户信息的批量新增、批量删除、批量查询 package com.java265.mapper; import com.java265.entity.UserInfo; import org.apache.ibatis.annotations.Delete; import org.apache.ibatis.annotations.Insert; import org.apache.ibatis.annotations.Param; import org.apache.ibatis.annotations.Select; import org.springframework.stereotype.Repository; import java.util.list; /** * 用户信息Mapper动态代理接口 * **/ @Repository public interface UserMapper { /** * 批量新增用户 */ @Insert({"<script>", "INSERT INTO tb_user(user_name,remark) VALUES", "<foreach collection='userInfoList' item='item' index='index' separator=','>", "(#{item.userName},#{item.remark})", "</foreach>", "</script>"}) public int addUserBatch(@Param("userInfoList") List<UserInfo> userInfoList); /** * 批量删除用户 */ @Delete({"<script>", "DELETE FROM tb_user WHERE user_id IN", "<foreach item='id' index='index' collection='array' open='(' separator=',' close=')'>", "#{id}", "</foreach>", "</script>"}) public int deleteUserBatch(int[] userIds); /** * 批量获取用户 */ @Select({"<script>", "SELECT * FROM tb_user WHERE user_id IN", "<foreach item='id' index='index' collection='array' open='(' separator=',' close=')'>", "#{id}", "</foreach>", "</script>"}) public List<UserInfo> getUserBatch(int[] userIds); } //批量新增 @Autowired private UserMapper userMapper; /** * 批量新增用户 * */ @Test public void addUserBatch() { //创建新用户列表 List<UserInfo> userInfoList = new ArrayList<UserInfo>(); userInfoList.add(new UserInfo("01","java265.com-1")); userInfoList.add(new UserInfo("02","java265.com-2")); userInfoList.add(new UserInfo("03","java265.com-3")); userInfoList.add(new UserInfo("04","java265.com-4")); //执行批量新增操作 int count = userMapper.addUserBatch(userInfoList); //打印结果 System.out.println("执行结果:成功新增" + count + "条数据!"); } //批量查询 @Autowired private UserMapper userMapper; /** * 批量获取用户 */ @Test public void getUserBatch() { //用户编号数组 int[] userIds = new int[]{1,2,3,4,5}; //执行批量获取操作 List<UserInfo> userInfoList = userMapper.getUserBatch(userIds); //打印结果 userInfoList.stream().forEach(System.out::println); } //批量删除 @Autowired private UserMapper userMapper; /** * 批量删除用户 */ @Test public void deleteUserBatch() { //用户编号数组 int[] userIds = new int[]{1,2,3,4,5}; //执行批量删除操作 int count = userMapper.deleteUserBatch(userIds); //打印结果 System.out.println("执行结果:成功删除" + count + "条数据!"); }
版权声明
本文仅代表作者观点,不代表本站立场。
本文系作者授权发表,未经许可,不得转载。