唯能极于情,故能极于剑
欢迎来到 “程序牛CodeCow” 的博客,有问题请及时关注小编公众号 “CodeCow”,大家一起学习交流
下面将为大家演示Mybatis通过注解方式对实体User进行批量添加、修改、删除。
1 public class User implements Serializable { 2 private Long id; //用户ID 3 private String name; //用户姓名 4 private Integer age; //用户年龄 5 ....... 6 }
2.1、批量插入用户
1 @Insert("<script>" + 2 "insert into user(id, name, age) VALUES " + 3 "<foreach collection=‘list‘ item=‘item‘ index=‘index‘ separator=‘,‘> " + 4 "(#{item.id},#{item.name},#{item.age}) " + 5 "</foreach>" + 6 "</script>") 7 void batchInsert(@Param("list")List<User> list); //批量添加用户
2.2、批量修改用户
1 @Update({"<script>" + 2 "<foreach collection=‘list‘ item=‘item‘ index=‘index‘ open=‘(‘ separator=‘,‘ close=‘)‘> " + 3 "update user set name= #{item.name}, age= #{item.age} " + 4 "where id = #{item.id} " + 5 "</foreach>" + 6 "</script>"}) 7 void batchUpdate(@Param("list")List<User> list);//批量修改用户
2.3、批量删除用户
1 @Delete("<script>" + 2 "delete from user where id in " + 3 "<foreach collection=‘array‘ item=‘id‘ open=‘(‘separator=‘,‘ close=‘)‘> " + 4 "#{id}" + 5 "</foreach>" + 6 "</script>") 7 void batchDelete(long[] ids);//批量删除用户 8 9 //☆☆☆ 如何获取 long[] ids ??? 10 //1、获取要删除用户的集合 11 List<User> user = userMapper.selectAll();//用的是tk.mybatis下获取所有用户 12 //2、根据集合获取 long[] ids 13 //朋友,如果你还在用遍历、创建数组等 SAO 操作.....你 OUT 了 14 //让我们看看jdk8的stream流是怎么搞的: 15 List<Long> idList = user.stream.map(User::getId).collect(Collectors.toList());//获取id集合 16 long[] ids = idList.stream.mapToLong(i -> i).toArray();// 获的long[] ids 17 18 就两步就实现了(其实就一步),它不香吗???
才疏学浅,有问题请及时关注小编公众号 “CodeCow”,大家一起学习交流
绳锯木断,水滴石穿 坚持
2020/04/13 早
原文:https://www.cnblogs.com/codecow/p/12693227.html