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="width:214px;background:#f3f3f3" maxlength="45">
<input id="roomCode" type="text" class="add_ftxt" placeholder="房间编号" style="width: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<){
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();
}

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

MP实战系列(十三)之批量修改操作(前后台异步交互)的更多相关文章

  1. MP实战系列(二)之集成swagger

    其实与spring+springmvc+mybatis集成swagger没什么区别,只是之前写的太不好了,所以这次决定详细写. 提到swagger不得不提rest,rest是一种架构风格,里面有对不同 ...

  2. MP实战系列(十二)之封装方法详解(续二)

    继续MP实战系列(十一)之封装方法详解(续一)这篇文章之后. 此次要讲的是关于查询. 查询是用的比较多的,查询很重要,好的查询,加上索引如鱼得水,不好的查询加再多索引也是无济于事. 1.selectB ...

  3. MP实战系列(七)之集成springboot

    springboot是现在比较流行的微服使用的框架,springboot本质上就是将spring+springmvc+mybatis零配置化,基本上springboot的默认配置符合我们的开发.当然有 ...

  4. MP实战系列(十四)之分页使用

    MyBatis Plus的分页,有插件式的,也有其自带了,插件需要配置,说麻烦也不是特别麻烦,不过觉得现有的MyBatis Plus足以解决,就懒得配置插件了. MyBatis Plus的资料不算是太 ...

  5. MP实战系列(九)之集成Shiro

    下面示例是在之前的基础上进行的,大家如果有什么不明白的可以参考MP实战系列的前八章 当然,同时也可以参考MyBatis Plus官方教程 建议如果参考如下教程,使用的技术为spring+mybatis ...

  6. MP实战系列(四)之DAO讲解

    说到DAO不得不提一个开发名词"三层架构",所谓的三层架构是什么呢?简单的可以概括为数据访问层,业务逻辑层,界面层(又称表现层). 这也是我们Java开发常用的手段,经常有人将三层 ...

  7. MyBatis批量修改操作

    1.需求 后台管理页面,查询频道列表,需要批量修改频道的状态,批量上线和下线 2.MyBatis配置 这是mysql的配置,注意需要加上&allowMultiQueries=true配置 jd ...

  8. MP实战系列(三)之实体类讲解

    首先说一句,mybatis plus实在太好用了! mybaits plus的实体类: 以我博客的用户类作为讲解 package com.blog.entity; import com.baomido ...

  9. MP实战系列(八)之SpringBoot+Swagger2

    SpringBoot一个原则,爱好编程的朋友们都知道,那就是"习惯优于配置". 今天一上来主要说的还是代码,个人比较喜欢来的实战系列的,不过有的时候还是比较偏重于理论,理论是造轮子 ...

随机推荐

  1. JavaScriptDay3

    js对标签的操作 创建标签:document.createElement("tag"); 便签添加内容 : document.createElement("tag&quo ...

  2. ORACLE查看数据库已安装补丁

    cd $ORACLE_HOME ./opatch lsinventory :}

  3. HDU2643(SummerTrainingDay05-P 第二类斯特林数)

    Rank Time Limit: 2000/1000 MS (Java/Others)    Memory Limit: 32768/32768 K (Java/Others)Total Submis ...

  4. 活字格Web应用平台学习笔记 6 - 使用公式

    发现学起来其实也花不了多少时间.继续学习下一节课:使用公式. 这应该会是高级一点的操作了吧,前面的几节课真是好简单好简单,简单到怀疑这是不是个技术人员该干的活,简单到怀疑人生~~ 这节课的目标: 好吧 ...

  5. [Java] 用 Comparator 实现排序

    最近正好用到Comparator,发现能对不同类型的对象进行排序(当然排序依据还是基本类型),也不用自己实现排序算法,用起来很方便,所以简单记录一下. 本文地址:http://www.cnblogs. ...

  6. [JAVA] 重写以及@Override标签

    以前JAVA看的少,最近做项目,对@Override的调用顺序有点疑惑,故查了一些资料.既然查资料了,那就把能看到的知识点整理一下,以供日后学习. 原文地址请保留http://www.cnblogs. ...

  7. JDK7下VisualVm插件无法链接到插件中心

      VisualVM 是一款免费的,集成了多个 JDK 命令行工具的可视化工具,它能为您提供强大的分析能力,对 Java 应用程序做性能分析和调优.这些功能包括生成和分析海量数据.跟踪内存泄漏.监控垃 ...

  8. Linux笔记(一):CentOS-7安装

     (一)   安装环境 VMware® Workstation 12 Pro,安装到物理机的话还需要做个U盘启动盘 (二)   下载 https://www.centos.org/download/ ...

  9. linux查看某IP尝试连接成功和失败次数

    查看连接失败次数 cat /var/log/secure | awk '/Failed/{print $(NF-3)}' | sort | uniq -c | awk '{print $2" ...

  10. python实现简单的负载均衡

    提到分发请求,相信大多数人首先会想到Nginx,Nginx作为一种多功能服务器,不仅提供了反向代理隐藏主机ip的能力,还拥有简单的缓存加速功能.当然Nginx最强大的功能还是分发请求,不仅提供了哈希, ...