We can only be passionate, so we can be extremely sword
Welcome to the blog of "Program Cow CodeCow", if you have any questions, please pay attention to the editor's public code " CodeCow " in time, everyone learn and communicate together
The following will demonstrate that Mybatis will add, modify, and delete entity users in batches through annotations.
First, the database entity DO
1 public class User implements Serializable { 2 private Long id; // User ID 3 private String name; // User name 4 private Integer age; // User age 5 ....... 6 }
2.1, insert users in batches
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, modify users in batches
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, delete users in batches
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); // Delete users in batches 8 9 // ☆☆☆ How to get long [] ids? ? ? 10 // 1. Get the collection of the user to be deleted 11 List <User> // 2, get long [] ids 13 according to the collection // friends, if you are still using SAO operations such as traversal, creating arrays, etc .... you are OUT 14 // let ’s see how the jdk8 stream is engaged Of: 15 List <Long> idList = user.stream.map (User :: getId) .collect (Collectors.toList ()); // Get the id collection 16 long [] ids = idList.stream.mapToLong (i-> i) .toArray (); // The obtained long [] ids 17 18 is realized in two steps (actually one step), is it not fragrant ? ? ?
Caishuxueqian, have questions, please concern small make public number " CodeCow ", we will study together the exchange
wire sawing off, dropping water adhere
2020/04/13 early