• MP实战系列(十三)之批量修改操作(前后台异步交互)


    MyBatis的批量操作其实同MyBatis基本是一样的。并无多大区别,要说区别,除了封装的方法之外,主要就是注解方面的区别,比如@TableId、@TableField、@TableName等等区别。

    示例描述:

    本次描述的是批量相关的操作,主要是批量修改等操作。

    项目讲解:如何批量修改开锁方式?

    准备环境和IDE工具:MySQL5.7+Maven3以上+JDK8或者JDK7+SSM框架+tomcat8或者tomcat7应用服务器+Eclipse。

    本文核心:主要是Controller代码和数据传输对象和js文件中的test2()方法内的ajax。

    其他的只是附加的,便于博主我个人以后回顾比较个人代码风格是否有所进步。我的理想是写一手优雅的代码。

    注意:特别是有经验的开发者们,本文核心代码可用供你们参考

    一、准备实体

    
    @TableName("`lock`")
    public class LockEntity implements Serializable {
        private static final long serialVersionUID = 1L;
    
        /**
         * 
         */
        private Integer id;
    
        @TableId
        private String lock_no;
    
        @TableField("house_code")
        private String houseCode;
     
        @TableField("room_code")
        private String roomCode;
      
        @TableField("install_time")
        private String installTime;
    
        @TableField("lock_kind")
        private Integer lockKind;
     
        private Integer power;
       
        @TableField("power_update_time")
        private String powerUpdateTime;
    
        @TableField("comu_status")
        private String comuStatus;
    
        @TableField("comu_status_update_time")
        private String comuStatusUpdateTime;
     
        private String region;
       
        private String address;
       
        @TableField("guarantee_time_start")
        private String guaranteeTimeStart;
     
        @TableField("guarantee_time_end")
        private String guaranteeTimeEnd;
    
        private Integer doorsensor;
      
        private String description;
     
        @TableField("hardware_version")
        private String hardwareVersion;
        
      
        private Integer type;
        
    
        @TableField("verify_code")
        private String verifyCode;
        
       
        private String no;
    
        @TableField("housing_code")
        private String housingCode;
        
     
        @TableField("first_open_way")
        private String firstOpenWay;
        
    
        @TableField("laster_open_way")
        private String lasterOpenWay;
      
        @TableField(value="node_no",exist=false)
        private String nodeNo;
       
        @TableField(value="user_id")
        private String userId;
        
    
        private Integer status;
        
        
        @TableField(exist=false)
        private String name;
    
        
       set get方法省略.... 
      }

    二、编写DAO

    public interface LockDao extends BaseMapper<LockEntity> {
        /**
         * 批量更新门锁开锁方式
         * @param lock
         * @return
         */
        public void updateLockOpenLockWayInfo(@Param ("lock") List<LockEntity> lock);
        
        
    }

    xml代码:

        
        <!-- 批量更新门锁开锁方式 -->
        <update id="updateLockOpenLockWayInfo" parameterType="java.util.List">
            <foreach collection="lock" item="lock" index="index" separator=";">
            update `lock`
            <set>
               first_open_way=#{lock.firstOpenWay},
               laster_open_way=#{lock.lasterOpenWay}
            </set>
            where id=#{lock.id}
        </foreach>      
            
        </update>
        
       

    三、编写Service代码

    public interface LockService extends IService<LockEntity> {
    
        /**
         * 批量更新门锁开锁方式
         * @param lock
         * @return
         */
        public void updateLockOpenLockWayInfo(@Param ("lock") List<LockEntity> lock);
    
    
    
        
    }

    四、编写Service实现类

    @Service("lockService")
    public class LockServiceImpl extends ServiceImpl<LockDao, LockEntity> implements LockService {
    
    
        @Override
        public void updateLockOpenLockWayInfo(List<LockEntity> lock) {
            // TODO Auto-generated method stub
            lockDao.updateLockOpenLockWayInfo(lock);
        }
    
    
    }

    五、Controller代码

    @RestController
    @RequestMapping("/lock")
    public class LockController {
    
        private static Logger logger = Logger.getLogger(LockController.class);
    
        @Autowired
        private LockService lockService;
    
        
    
        /**
         * 批量修改开锁方式
         * @param openLockWayQueryVoy
         * @return
         */
        @PostMapping(value="/updateLockOpenLockWayInfo",produces="application/json;charset=utf-8")
        public Object batchUpdateLockOpenLockWayInfo(@RequestBody OpenLockWayQueryVo openLockWayQueryVo) {
    
            
            Integer ids[]=openLockWayQueryVo.getIds();
            String items[]=openLockWayQueryVo.getItems();
            String items2[]=openLockWayQueryVo.getItems2();
            JSONObject json = new JSONObject();    
            
            try {
                String str="";
                for (int i = 0; i < items.length; i++) {
                    if(items[i].equals("on")) {
                        items[i]="0";
                    }else if(items[i].equals("0")) {
                        items[i]="1";
                    }
                    str+=items[i];
                    logger.info("items[i]:"+str);
                    
                }
                String str2="";
                for (int j = 0; j < items2.length; j++) {
                    if(items2[j].equals("on")) {
                        items2[j]="0";
                    }else if(items2[j].equals("0")) {
                        items2[j]="1";
                    }
                    str2+=items2[j];
                    logger.info("items2[i]:"+str2);
                    
                }
                
                String first=str+"00000";
                logger.info("first:"+first);
                
                String laster=str2+"00000";
                logger.info("laster:"+laster);
                
                for (int i = 0; i < ids.length; i++) {
                    logger.info("ids[i]:"+ids[i]);
                    LockEntity lockEntity = new LockEntity();
                    lockEntity.setId(ids[i]);
                    lockEntity.setFirstOpenWay(first.substring(0,8));
                    lockEntity.setLasterOpenWay(laster.substring(0,8));
                    List<LockEntity> list = new ArrayList<LockEntity>();
                    list.add(lockEntity);
                    
                    //批量修改方法调用
                    lockService.updateLockOpenLockWayInfo(list);
                    
                }
                json.put("returnMsg", "批量修改成功");
                json.put("returnCode", "000000");
            } catch (Exception e) {
                e.printStackTrace();
                json.put("returnMsg", "批量修改失败");
                json.put("returnCode", "111111");
            }
            
        
            
            return json;
            
    
        }
    }

    六、编写数据传输对象

    public class OpenLockWayQueryVo{
    
        
        Integer ids[];
     
        String items[];
        
        String items2[];
        
        set get方法此处省略....
        
    }

    七、前端HTML代码

    <!DOCTYPE html>
    <html lang="zh-cmn-Hans">
    <head>
    <!--     <script src="../js/tologin.js"></script> -->
        <meta charset="UTF-8">
        <meta content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=0" name="viewport">
        <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1" />
        <meta name="renderer" content="webkit">
        <meta http-equiv="Cache-Control" content="no-siteapp" />
        <link type="image/x-icon" href="/../images/fav.ico?rel=1522142498852" rel="shortcut icon"/>
        <link rel="stylesheet" href="../fonticon/iconfont.css?rel=1522142498852" />
        <link rel="stylesheet" href="../css/normalize.min.css?rel=1522142498852"/>
        <link rel="stylesheet" href="../css/app.min.css?rel=1522142498852"/>
        <link rel="stylesheet" href="../css/lock-css.min.css?rel=1522142498852"/>
        <link rel="stylesheet" href="../css/node-css.min.css?rel=1522142498852"/>
        <link rel="stylesheet" href="../css/common.min.css?rel=1522142498852"/>
        <link rel="stylesheet" href="../js/limarquee/liMarquee.css"/>
        <link rel="stylesheet" href="../css/ammeter-css.min.css"/>
        <link rel="stylesheet" href="../layui/css/modules/layer/default/layer.css" media="all">
        
        
    <title>批量修改开锁方式</title>
    <style>
        #menu li[data-body='lockList'],#menu li[data-body='nodeList'],#menu li[data-body='index']{
            display: none;
        }
        .yw_list table th {
            font-size: 12px;
            background-color: #dcdcdc;
            height: 36px;
            line-height: 36px;
        }
        .yw_list table td {
            text-align: center;
            font-size: 12px;
            color: #1f2f3e;
            height: 38px;
            word-break: break-all;
            word-wrap: break-word;
            line-height: 20px;
            border:1px #ddd solid;
        }
        .yw_list table tr:nth-child(odd){background:#f3f3f3;}
        .yw_list table tr:nth-child(even){background:#fff;}
    </style>
        <script src="../js/baiduTemplate.js"></script>
    <body>
    
    <div class="warper" data-body="userManage">
    
        <!--s: sidebar-->
    <div class="sidebar" id="sidebar">
      <a href="javascript:;" id="showBar"><i class="iconfont icon-icon-test15"></i></a>
      <div class="user-pic">
        <div class="user-picn">
          <span id="applytop-div-wrap-user" class="applytop-div-wrap" style="background: url('../images/3-30.png') no-repeat center; -webkit-background-size: cover;-moz-background-size: cover;-ms-background-size: cover;background-size: cover;">
          </span>
          <span class="png6"></span>
        </div>
        <p id="sidebarName"></p>
      </div>
      <ul class="menu" id="menu">
        <!--<li data-body="home" style="display: none;"><a class="png6" href="home.html"><em class="iconfont icon-pingtai" style="position: relative;right: -4px;"></em><span>平台主页</span></a></li>-->
        <li data-body="lockList" style="display: block;"><a class="png6" href="lockList.html"><em class="iconfont icon-icon-test" style="position: relative;right: -4px;"></em><span>智能门锁</span></a></li>
        <li data-body="nodeList" style="display: block;"><a class="png6" href="nodeList.html"><em class="iconfont icon-icon-test2"></em><span>智能网关</span></a></li>
        <li data-body="ammeterList" style="display: none;"><a class="png6" href="ammeterList.html"><em class="iconfont icon-dianbiao1"  style="vertical-align:middle;font-size:25px"></em><span>智能电表</span></a></li>
        <li data-body="userManage" class="menu-f" style="display:none;"><a class="png6" href="userManageList.html"><em class="iconfont icon-guanli" style="font-size: 1.8em;position:relative;top:4px;"></em><span style="padding-left:5px;">审批管理</span></a></li>
        <li data-body="mySet"><a href="mySet.html"><em class="iconfont icon-icon-test1"></em><span>个人中心</span></a></li>
        <li data-body="index" class="menu-f" style="display: block;"><a class="png6" href="index.html"><em class="iconfont icon-icon-test11"></em><span>统计分析</span></a></li>
      </ul>
    </div><!--e: sidebar-->
    
    <!--s: toper-->
    <div class="toper">
      <div class="icon"><img src="../images/3-30.png" width="80" height="60" alt=""></div>
      <div class="loginout" >
        <a class="png6" href="javascript:;" id="link_loginOut"><i class="iconfont icon-icon-test9"></i><span id="exit">退出</span></a>
      </div>
    </div><!--e: toper-->
    
    <!--通知-->
    <div id="pageInfo"><div class="dowebok" id="marTxt"></div></div>
    
      <!--s: container-->
      <div class="container" id="container">
    
        <div class="h60"></div>
    
        <!--s: main-->
        <div class="main">
    
            <h2 class="titpos"><span class="curpage">批量修改管理</span></h2>
          <!--s: part-3-->
    
            <h3 class="clrfix subtit subtitmargin combox" style="padding:10px 0 10px 30px;">
                <i class="fl subtit-l" id="yw_9">
                    <input id="houseCode" type="text" class="add_ftxt" placeholder="房源编号" style="214px;background:#f3f3f3" maxlength="45">
                     <input id="roomCode" type="text" class="add_ftxt" placeholder="房间编号" style="214px;background:#f3f3f3" maxlength="45">
                    <a class="addbtn red" id="J_addSearch_hong" href="javascript:;" style="margin-right:50px;margin-left:8px;">搜索</a>
                    <button class="layui-btn" style="float:right;" onclick="test()">开锁方式批量设置</button>
                </i>
                <span class="fr wordicos" style="margin-top:7px; display: none;">
                    <span class="word_w" id="locknum_1"><span class="red" id="rows"></span> 条数据</span>
                </span>
            </h3>
    
          <div id="user_search" class="clrfix part-s part-3 combox" style="display: none;">
    
            <ul class="ful lockmnglist lockmnglist2" id="forSelect1"></ul>
    
          </div><!--e: part-3-->
    
            <div id="yw_list" class="clrfix part-s yw_list combox">
                <span style="line-height: 40px;">数据列表</span>
                <table class="alert-tb tdh60" width="100%" cellpadding="0" cellspacing="0" border="0">
                    <thead>
                    <tr>
                        <tr>
                        <th width="60">选择</th>
                        <th>门锁编码</th>
                        <th>房源编码</th>
                        <th width="150">房间编码</th>
                        <th width="100">门锁类型</th>
                        <th width="100">是否支持门磁</th>
                        <th width="100">通信状态</th>
                         <th width="100">电池电量</th>
                         <th width="100">安装地址</th>
                        <th width="100">安装时间</th>
                        <th width="100">运营商</th>
                        <th width="100">网关</th>
                        <th width="100">操作</th>            
                    </tr>
                    </thead>
                    <tbody id="list">
                        
                    </tbody>
                </table>
            </div>
          <!--s: pages-->
        
    
        </div><!--e: main-->
    
        <div class="h60"></div>
    
      </div><!--e: container-->
    
    
    </div>
    
    
    <!--s: over-->
    <div class="over" id="over"></div>
    <!--e: over-->
    
    <!--s: dialog-->
    <div class="msg" id="msg">
        <div class="msgtit" style="background:#e70012"><p style="color:#fff;"></p><a href="javascript:;" title="点击关闭">X</a></div>
        <div class="msgcon">
            <div class="msginner">
                <div tabindex="5" class="confirm"></div><!--alert confirm dialog-->
            </div>
        </div>
    </div>
    <!--js-->
    <script src="../js/jquery-1.11.3.min.js"></script>
    <script src="../js/jquery.cookie.min.js"></script>
    <script src="../js/common/common.js"></script>
    <script src="../layui/layui.js" charset="utf-8"></script>
    <script type="text/javascript" src="../js/common/common.js"></script>
    <script type="text/javascript" src="../js/lock/companyLockList.js"></script>
    <div id="ldings" class="ldings">
        <span></span>
    </div>
    
    </body>
    </html>

    八、主要核心js代码

    
       
       function test2(){
           var ids = [];//定义一个门锁编号空数组
           
           //初次开锁方式空数组
           var items = [];
           
           //后续开锁方式空数组
           var items2=[]
          
         $("input[name='lock_id']:checked").each(function(i){//把所有被选中的复选框的值存入数组
             ids[i] =$(this).val();
             
         });
              
                   
         $("input[name='first_way']").each(function() {
            
             items.push($(this).val());
    
         });
         
         $("input[name='laster_way']").each(function() {
                
             items2.push($(this).val());
    
         });
    
    
                 
        var first = $('input[name="first_way"]:checked').length;
        var laster = $('input[name="laster_way"]:checked').length;
        
        if(first<2){
            layui.use('layer', function(){
                  var layer = layui.layer;
                  
                  layer.alert("初次开锁方式至少选择两种");
            });
            
            return false;
        }else if(laster<2){
            
            layui.use('layer', function(){
                  var layer = layui.layer;
                  
                  layer.alert("后续开锁方式至少选择两种");
            });
          
          return false;
        }else{
            
            var data = {
                    ids:ids,
                    items:items,
                    items2:items2
            }
            $.ajax({
    
                url: "/lms/lock/updateLockOpenLockWayInfo",
                type: "POST",
                contentType: 'application/json;charset=utf-8',
                data : JSON.stringify(data),
                dataType : 'json',            
                success: function(data){
                    if(data.returnCode=="000000"){
                      layui.use('layer', function(){
                        var layer = layui.layer;
                        
                        layer.msg(data.returnMsg,{icon:1});
                  });
                      setTimeout(() => {
                          
                          closeLayui();
                    }, 800);
                    }else{
                      layui.use('layer', function(){
                          var layer = layui.layer;
                          
                          layer.alert(data.returnMsg,{icon:5});
                    });
                    }
                },error:function(XMLHttpRequest, textStatus, errorThrown){
                   // 状态码
                     alert(XMLHttpRequest.status);
                      // 状态
                      alert(XMLHttpRequest.readyState);
                      // 错误信息   
                      alert(textStatus);
                }
    
              });
           
            
            return true;
        }
             
            
       }
       
      
       //关闭layui弹框
       function closeLayui(){
           parent.layer.closeAll()
           location.reload();
      }
      
        

    小结:通过上述例子,即可完成批量修改功能。

  • 相关阅读:
    PCA理论与实践
    深度挖掘客户价值—分析角度篇
    多元线性回归理论与实践
    数据分析框架
    Growing转化的每一步(笔记整理)
    kmeans算法原理以及实践操作(多种k值确定以及如何选取初始点方法)
    mysql查询优化(持续更新中)
    mysql 各种运算对于null值的处理
    left join与on,where 结合一起用的异同
    Spark(十一) -- Mllib API编程 线性回归、KMeans、协同过滤演示
  • 原文地址:https://www.cnblogs.com/youcong/p/9356495.html
Copyright © 2020-2023  润新知