经验首页 前端设计 程序设计 Java相关 移动开发 数据库/运维 软件/图像 大数据/云计算 其他经验
当前位置:技术经验 » 数据库/运维 » MyBatis » 查看文章
MyBatis foreach 批量更新实例
来源:jb51  时间:2021/1/25 11:27:16  对本文有异议

在做配置选项(设备类型,所属楼层等)的时候,当删除某配置的时候,我需要检验该配置是否已被删除。

  1. @Override
  2. public BaseVO deleteOptionDetail(Integer id) {
  3. // 合法性验证
  4. if (null == id) {
  5. return ParamErrorVO.getInstance();
  6. }
  7. ConfigOptionDetail configOptionDetail = configOptionDetailMapper.selectById(id);
  8. if (null == configOptionDetail || 1 == configOptionDetail.getIsDeleted()) {
  9. return new ErrorVO("该配置不存在");
  10. }
  11. if (configOptionDetail.getSystem() == 1) {
  12. return new ErrorVO("系统属性不能删除");
  13. }
  14. if (configOptionDetail.getUseCount() = 0) {
  15. return new ErrorVO("配置正在使用不能删除,请先删除使用配置的地方");
  16. }
  17. // 合法性通过
  18. configOptionDetail.setIsDeleted(1);
  19. configOptionDetail.setGmtModefied(Calendar.getInstance().getTime());
  20. configOptionDetailMapper.updateById(configOptionDetail);
  21. // 更新内存配置
  22. ConfigOptionConstruct.updateOption();
  23. return SuccessVO.getInstance();
  24. }

思考之后我决定采用,给配置选项设备一个use_count字段,代表该配置被引用的次数。 只有当该字段值为 0 时,该配置选项记录才可被删除。

使用情况:

我需要批量删除房间, 删除房间的同时,room对象中使用到了所属楼层的配置选项,我需要将他们的引用减少

  1. @Override
  2. public BaseVO deleteRoomByIds(Integer[] ids) {
  3. if (null == ids) {
  4. return ParamErrorVO.getInstance();
  5. }
  6. EntityWrapper<Room> entityWrapper = new EntityWrapper<>();
  7. entityWrapper.where("isdelete={0}", 0);
  8. // 核查删除的房间中是否存在正在使用的设备
  9. List<Integer> notDelete = deviceInfoService.checkRoomIds(ids);
  10. if (null != notDelete && 0 != notDelete.size()) {
  11. // 存在仍在使用设备的房间
  12. entityWrapper.in("id", notDelete);
  13. // 查询这些房间
  14. List<Room> roomList = roomMapper.selectList(entityWrapper);
  15. // 获取房间的名称
  16. StringBuilder stringBuilder = new StringBuilder(roomList.stream().map(Room::getName).collect(Collectors.toList()).toString());
  17. System.out.println(stringBuilder);
  18. // TODO: 2018/4/8 可能需要修改提示语
  19. return new ErrorVO(stringBuilder + " 房间存在未删除的设备,请先删除设备");
  20. }
  21. // 房间没有设备在使用
  22. List<Integer> idList = new ArrayList<>();
  23. idList.addAll(Arrays.asList(ids));
  24. // 查询需要删除的房间
  25. entityWrapper.in("id", idList);
  26. List<Room> roomList = roomMapper.selectList(entityWrapper);
  27. if (null == roomList || idList.size() != roomList.size()) {
  28. return new ErrorVO("存在错误的房间");
  29. }
  30. // ******************************************************************************************** 重点
  31. // 可以逻辑删除
  32. int count = roomMapper.logicDeleteByIds(idList);
  33. List<Long> optionIds = roomList.stream().map(room -> Long.parseLong(room.getRoomPosition())).collect(Collectors.toList());
  34. Map<Long, Long> optionIdsMap = optionIds.stream().collect(Collectors.groupingBy(p -> p,Collectors.counting()));
  35. // 移除所属楼层配置选项的使用
  36. configOptionDetailService.removeUseCount(optionIdsMap);
  37. ConfigOptionConstruct.updateOption();
  38. if (count == idList.size()) {
  39. return SuccessVO.getInstance();
  40. } else {
  41. return new ErrorVO("部分删除失败");
  42. }
  43. }

optionIds 是从roomList 房间集合中,通过stream, 所引用的配置选项id集合

上面我红字标明他们,是因为,如果房间A 是一楼, 房间B 也是一楼, 那么我应该将一楼的引用减 2。

所以我将optionIds 分组转成Map<配置选项id, 需要减少引用的次数>

最后一步,也是最重要的进行数据库操作,我希望可以批量更新减少这些引用。

查看MyBatis文档:

foreach

动态 SQL 的另外一个常用的操作需求是对一个集合进行遍历,通常是在构建 IN 条件语句的时候。比如:

  1. <select id="selectPostIn" resultType="domain.blog.Post">
  2. SELECT *
  3. FROM POST P
  4. WHERE ID in
  5. <foreach item="item" index="index" collection="list"
  6. open="(" separator="," close=")">
  7. #{item}
  8. </foreach>
  9. </select>

foreach 元素的功能非常强大,它允许你指定一个集合,声明可以在元素体内使用的集合项(item)和索引(index)变量。它也允许你指定开头与结尾的字符串以及在迭代结果之间放置分隔符。这个元素是很智能的,因此它不会偶然地附加多余的分隔符。

注意 你可以将任何可迭代对象(如 List、Set 等)、Map 对象或者数组对象传递给 foreach 作为集合参数。当使用可迭代对象或者数组时,index 是当前迭代的次数,item 的值是本次迭代获取的元素。当使用 Map 对象(或者 Map.Entry 对象的集合)时,index 是键,item 是值。

  1. <update id="addUseCountByIds">
  2. update config_option_detail
  3. set gmt_modified = #{gmtModified}, use_count = use_count +
  4. <foreach item="item" index="index" collection="list" open=" case id " separator=" " close=" end">
  5. when #{index} then #{item}
  6. </foreach>
  7. where id in
  8. <foreach item="item" index="index" collection="list"
  9. open="(" separator="," close=")">
  10. #{index}
  11. </foreach>
  12. </update>

补充:mybatis 用<foreach>根据ID批量更新时的一个注意点。

看接口。传入一个Long型的List。

  1. int updateReadCount(@Param(value = "topicIdList") List<Long> topicIdList);

xml里面循环update.

  1. <update id="updateReadCount" parameterType="java.util.List">
  2. update CTS
  3. set read_count = read_count + 1
  4. where topic_id in
  5. <foreach item="item" index="index" collection="topicIdList" open="(" close=")" separator=",">
  6. #{item.topicId}
  7. </foreach>
  8. </update>

就是直接复制了别人的代码,改了一改。怎么都跑不通。。。。。。。

问题就出在这个item,item 表示集合中每一个元素进行迭代时的别名。

List<Long> topicIdList 因为时Long型(不是entity封装着的),就不需要别名了。改为如下就可以跑通了。

  1. <update id="updateReadCount" parameterType="java.util.List">
  2. update CTS
  3. set read_count = read_count + 1
  4. where topic_id in
  5. <foreach item="topicId" index="index" collection="topicIdList" open="(" close=")" separator=",">
  6. #{topicId}
  7. </foreach>
  8. </update>

以上为个人经验,希望能给大家一个参考,也希望大家多多支持w3xue。如有错误或未考虑完全的地方,望不吝赐教。

 友情链接:直通硅谷  点职佳  北美留学生论坛

本站QQ群:前端 618073944 | Java 606181507 | Python 626812652 | C/C++ 612253063 | 微信 634508462 | 苹果 692586424 | C#/.net 182808419 | PHP 305140648 | 运维 608723728

W3xue 的所有内容仅供测试,对任何法律问题及风险不承担任何责任。通过使用本站内容随之而来的风险与本站无关。
关于我们  |  意见建议  |  捐助我们  |  报错有奖  |  广告合作、友情链接(目前9元/月)请联系QQ:27243702 沸活量
皖ICP备17017327号-2 皖公网安备34020702000426号