唯能極於情,故能極於劍
文:MyBatis通過注解方式批量添加、修改、刪除
注:有空看看小編:CodeCow · 程序牛
的個人技術博客吧:http://www.codecow.cn/
《 繩鋸木斷,水滴石穿 —— 多堅持 》
一、數據庫實體DO
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 早