❤️SSM+MySQL动态批量新增,更新,删除
mybatis动态批量新增,更新,删除
mybatis动态批量新增,更新,删除 (spring+springmvc+mybatis+maven+mysql)
1.连接mysql的文件加上批处理的配置 [批量新增和更新可以参照多个对象批量删除,这个只有批量删除的例子,但批量新增和更新只有mapper.xml文件不一样,只需要单独的更新和新增方法就可以,jsp页面多个对象传值都是一样的实现方式]
jdbc.user=root
jdbc.password=root
jdbc.url=jdbc:mysql://localhost:3306/work_project?allowMultiQueries=true&rewriteBatchedStatements=true&useUnicode=true&characterEncoding=utf8
jdbc.driver=com.mysql.jdbc.Driver
2.获取jsp文件里多个对象的值,异步ajax提交。(两种方式实现批量删除,一个是只有id的数组传值,另一个是多个对象传值[批量更新和新增也可参照这个])
2.1 jsp页面动态拼接函数(我这个例子是把对象的多个属性值都放到一个input里了,批量更新和新增可以把单个的属性放到每一行td的input标签里)
var html = "";
$.each(pageData,
function(i, n) {
html += '<tr>';
html += ' <td>' + (i + 1) + '</td>';
html += ' <td><input type="checkbox" id="' + n.id + '" name="' + n.username + '" email="' + n.email + '" loginacct="' + n.loginacct + '"></td>'; //这里是批量删除的关键
html += ' <td>' + n.loginacct + '</td>';
html += ' <td>' + n.username + '</td>';
html += ' <td>' + n.email + '</td>';
html += ' <td>';
html += ' <button type="button" class="btn btn-success btn-xs"><i class=" glyphicon glyphicon-check"></i></button>';
html += ' <button type="button" class="btn btn-primary btn-xs" onclick="window.location.href=\'${CWF_PATH}/user/toUpdate.htm?id=' + n.id + '\'"><i class=" glyphicon glyphicon-pencil"></i></button>';
html += ' <button type="button" class="btn btn-danger btn-xs" onclick="deleteUser(' + n.id + ',\'' + n.username + '\')"><i class=" glyphicon glyphicon-remove"></i></button>';
html += ' </td>';
html += '</tr>';
});
$("#tbodyConcat").html(html);
2.1.2 ajax异步提交,方式1(只有id的数组传值)。

function deleteBatch() {
var selectedCheckBox = $("#tbodyConcat input:checked"); //根据选中的checkbox取得所有要删除的数据的集合
if (selectedCheckBox.length <= 0) {
layer.msg("请选择要删除的数据!", {
time: 1000,
icon: 6,
shift: 6
});
return false;
}
var idStr = ""; //数组方式,定义传值的变量(根据ajax的data属性设置的,具体看上边的图)
$.each(selectedCheckBox,
function(i, n) {
//数组方式
if (0 != i) {
idStr += "&";
}
idStr += "ids=" + n.id; //后台必须以ids接收(这里如果是abc,后台接收变量也要是abc)
});
layer.confirm("确认要删除这些用户吗", {
icon: 3,
title: "提示"
},
function(confirmIndex) {
layer.close(confirmIndex);
$.ajax({
type: "POST",
contentType: 'application/json;charset=utf-8',
//设置请求头信息
dataType: "json",
data: idStr,
//数组方式
url: "${CWF_PATH}/user/deleteBatch.do",
beforeSend: function() {
return true;
},
success: function(data) {
if (data.success) {
window.location.href = "${CWF_PATH}/user/toIndex.htm";
} else {
layer.msg(data.message, {
time: 1000,
icon: 6,
shift: 6
});
}
},
errot: function() {
layer.msg("删除数据失败!", {
time: 1000,
icon: 6,
shift: 6
});
}
});
},
function(confirmIndex) {
layer.close(confirmIndex);
}
);
}
java后台deleteBatch方法(controller文件,这里service和dao不展示,只展示mapper.xml文件的方法)
//注意这里的ids必须和jsp页面[idStr += "ids="+n.id;]的ids一致,
//而不是ajax的[data:idStr,]的idStr
@ResponseBody@RequestMapping("/deleteBatch")
public Object deleteBatch(Integer[] ids) {
AjaxResult result = new AjaxResult();
try {
int count = userService.deleteBatch(ids);
if (count == ids.length) {
result.setSuccess(true);
result.setMessage("删除成功");
}
} catch(Exception e) {
result.setSuccess(false);
result.setMessage("删除失败");
e.printStackTrace();
}
return result;
}
mapper文件
int deleteBatchUser(@Param("ids") Integer[] id); // collection="ids")
mapper.xml文件
<?xml version="1.0" encoding="utf-8"?>
<!-- collection="array" 如果参数是数组,采用默认"array"名你获取数组参数.
collection="list" 如果参数是集合,采用默认"list"名你获取集合参数.
collection="具体名可以根据dao接口的@Param设置" 例如:int deleteBatchUser(@Param("ids") Integer[] id); // collection="ids"-->
<delete id="deleteBatch">delete from t_user where id in
<foreach collection="array" item="id" separator="," open="(" close=")">#{id}</foreach>
</delete>
2.2多个对象传值方式
2.2.1 jsp页面动态拼接函数(我这个例子是把对象的多个属性值都放到一个input里了,批量更新和新增可以把单个的属性放到每一行td的input标签里)
var html = "";
$.each(pageData,
function(i, n) {
html += '<tr>';
html += ' <td>' + (i + 1) + '</td>';
html += ' <td><input type="checkbox" id="' + n.id + '" name="' + n.username + '" email="' + n.email + '" loginacct="' + n.loginacct + '"></td>'; //这里是批量删除的关键
html += ' <td>' + n.loginacct + '</td>';
html += ' <td>' + n.username + '</td>';
html += ' <td>' + n.email + '</td>';
html += ' <td>';
html += ' <button type="button" class="btn btn-success btn-xs"><i class=" glyphicon glyphicon-check"></i></button>';
html += ' <button type="button" class="btn btn-primary btn-xs" onclick="window.location.href=\'${CWF_PATH}/user/toUpdate.htm?id=' + n.id + '\'"><i class=" glyphicon glyphicon-pencil"></i></button>';
html += ' <button type="button" class="btn btn-danger btn-xs" onclick="deleteUser(' + n.id + ',\'' + n.username + '\')"><i class=" glyphicon glyphicon-remove"></i></button>';
html += ' </td>';
html += '</tr>';
});
$("#tbodyConcat").html(html);
2.2.2 ajax异步提交,方式2(多个对象的数组传值,批量更新和新增可以参照这个)。
function deleteBatch() {
var selectedCheckBox = $("#tbodyConcat input:checked"); //根据选中的checkbox取得要删除(更新和新增)的集合
if (selectedCheckBox.length <= 0) {
layer.msg("请选择要删除的数据!", {
time: 1000,
icon: 6,
shift: 6
});
return false;
}
var jsonData = new Array(); //定义要删除(更新和新增)数据的数组,将页面的多个对象数据存放到这个数组
//循环集合,根据attr取得input里的各个属性值。(如果是新增和修改,需要根据取得的当前对象去获取其他input的text属性的值:可以用jQuery的parent加fing方式去获取,具体可以去百度)
$.each(selectedCheckBox,
function(i, n) {
var that = this;
//把取得的多个对象的值push到数组里,注意这里的key要和User实体类的属性一致
jsonData.push({
"id": $(that).attr("id"),
"loginacct": $(that).attr("loginacct"),
"username": $(that).attr("name"),
"email": $(that).attr("email")
});
});
layer.confirm("确认要删除这些用户吗", {
icon: 3,
title: "提示"
},
function(confirmIndex) {
layer.close(confirmIndex);
$.ajax({
type: "POST",
contentType: 'application/json;charset=utf-8',
//设置请求头信息
dataType: "json",
data: JSON.stringify(jsonData),
//将Json对象序列化成Json字符串,JSON.stringify()原生态方法
url: "${CWF_PATH}/user/deleteBatch.do",
beforeSend: function() {
return true;
},
success: function(data) {
if (data.success) {
window.location.href = "${CWF_PATH}/user/toIndex.htm";
} else {
layer.msg(data.message, {
time: 1000,
icon: 6,
shift: 6
});
}
},
errot: function() {
layer.msg("删除数据失败!", {
time: 1000,
icon: 6,
shift: 6
});
}
});
},
function(confirmIndex) {
layer.close(confirmIndex);
}
);
}
java后台deleteBatch方法(controller文件,这里service和dao不展示,只展示mapper.xml文件的方法)
注意接收参数的地方要加 @RequestBody
//前台数组传输
@ResponseBody
@RequestMapping("/deleteBatch")
public Object deleteBatch(@RequestBody List<User> users){
AjaxResult result = new AjaxResult();
try {
int count = userService.deleteBatchByList(users);
if(count == users.size()){
result.setSuccess(true);
result.setMessage("批量删除成功");
}
} catch (Exception e) {
result.setSuccess(false);
result.setMessage("批量删除失败");
e.printStackTrace();
}
return result;
}
mapper.xml文件的方法(批量更新和新增的话只需要把insert和update的方法加上就可以了,也是用foreach的方式,不会的去百度)
mapper接口
int deleteBatchByList(List<User> users);
<delete id="deleteBatchByList">delete from t_user where id in
<foreach collection="list" item="user" separator="," open="(" close=")">#{user.id}</foreach>
</delete>
=========新增Mapper.xm文件方法例子(写法不同,配置文件不同)================================
注意如果不都写在foreach里,数据库连接文件可以不加allowMultiQueries=true&rewriteBatchedStatements=true
insert into t_user_role(userid,roleid) values
<foreach collection="list" item="entity" index="index"
separator=",">
(#{entity.id},#{entity.roleId})
</foreach>
注意如果写在都foreach里, 数据库连接文件必须加allowMultiQueries=true&rewriteBatchedStatements=true
<foreach collection="list" item="user" separator=";">
**insert into t_user_role(userid,roleid) values(#{user.id},#{user.roleId})**
</foreach>
上边的改进版(先判断在更新)
<foreach collection="list" item="user" separator=";">insert into t_user_role
<trim prefix="(" suffix=")" suffixOverrides=",">
<if test="user.id != null">userid,</if>
<if test="user.roleId != null">roleid,</if>
</trim> values
<trim prefix="(" suffix=")" suffixOverrides=",">
<if test="user.id != null">#{user.id,jdbcType=INTEGER},</if>
<if test="user.roleId != null">#{user.roleId,jdbcType=INTEGER}</if>
</trim>
</foreach>
