mybatis批量新增、删除、查询和修改方式
作者:xuforeverlove 发布时间:2023-11-23 10:13:01
每次写批量的时候,都要在网上搜索一下,虽然都做过多次了,但具体的自己还是记不住(汗颜),所以索性今天就记录下来。
前期说明:
foreach的主要用在构建in条件中,它可以在SQL语句中进行迭代一个集合。foreach元素的属性主要有 item,index,collection,open,separator,close。
item表示集合中每一个元素进行迭代时的别名,index指 定一个名字,用于表示在迭代过程中,每次迭代到的位置,open表示该语句以什么开始,separator表示在每次进行迭代之间以什么符号作为分隔 符,close表示以什么结束,在使用foreach的时候最关键的也是最容易出错的就是collection属性,该属性是必须指定的,但是在不同情况 下,该属性的值是不一样的
主要有一下3种情况:
1.如果传入的是单参数且参数类型是一个List的时候,collection属性值为list
2.如果传入的是单参数且参数类型是一个array数组的时候,collection的属性值为array
3.如果传入的参数是多个的时候,我们就需要把它们封装成一个Map了,当然单参数也可以封装成map,实际上如果你在传入参数的时候,在breast里面也是会把它封装成一个Map的,map的key就是参数名,所以这个时候collection属性值就是传入的List或array对象在自己封装的map里面的key
(1)mybatis批量新增
mapper.xml
<insert id="createBatchUserInfoList" useGeneratedKeys="true" parameterType="java.util.List" >
insert into
el_user_info (id,user_name,user_tel,pass_word,user_sex,del_mark,position_id,agency_id,create_date,update_date,role_id,employee_id,org_id)
values
<foreach collection="list" item="item" index="index" separator="," >
(#{item.id},#{item.userName},#{item.userTel}, #{item.passWord},#{item.userSex},
#{item.delMark},#{item.positionId},#{item.agencyId},#{item.createDate},#{item.updateDate},#{item.roleId},#{item.employeeId},#{item.orgId})
</foreach>
</insert>
mapper:
/**
* 批量插入
*
* @param list
* @return
*/
int createBatchUserInfoList(List<ElUserInfo> list);
serviceImpl实现类:
try {
List<ElUserInfo> userList = new ArrayList<ElUserInfo>();
if (CollectionUtils.isNotEmpty(list)) {
//组织id
Long orgId = elAppInfoService.getOrg().getOrgId();
for (int i = 0; i < list.size(); i++) {
Map<String, Object> map = list.get(i);
String userSex = map.get("userSex").toString().trim();
String userName = map.get("userName").toString().trim();
String userTel = map.get("userTel").toString().trim();
String key = userName + userTel;
String redisCacheByKey = redisCacheService.getRedisCacheByKey(key);
log.info(redisCacheByKey);
if (!StringUtils.isEmpty(redisCacheByKey)) {
//redisCacheService.deleteRedisCacheByKey(key);
continue;
}
if ("男".equals(userSex)) {
userSex = "0";
} else if ("女".equals(userSex)){
userSex = "1";
}
ElUserInfo user = new ElUserInfo();
user.setUserName(userName);
user.setUserTel(userTel);
user.setPassWord(MD5(map.get("passWord").toString().trim()));
user.setUserSex(userSex);
user.setPositionId(postionId);
user.setAgencyId(agencyId);
user.setCreateDate(new Date());
user.setUpdateDate(new Date());
user.setDelMark(0);
user.setRoleId(1L);
user.setEmployeeId(0L);
user.setOrgId(orgId);
userList.add(user);
}
if (CollectionUtils.isNotEmpty(userList)) {
//先持久化本地
row = userInfoMapper.createBatchUserInfoList(userList);
if (row > 0) {
//持久化成功后同步组织平台
String add = orgEmployeeService.addOrganRoleUserToPlatform(userList, "add");
if (!StringUtils.isEmpty(add) && !"-1".equals(add) && !"null".equals(add)) {
//以用户手机号码为唯一标示,批量修改OrgId和EmployeeId
userInfoMapper.updateBatchOrgId(userList);
}
log.info(this.getClass().getName()+"的UserInfoThread"+add.toString());
}
}
}
} catch (Exception e) {
log.error("elPositionInfoServiceImpl的UserInfoThread方法error"+e.getMessage(),e);
}
(2)mybatis批量删除
mapper.xml:
<delete id="batchDeleteUser">
delete from t_user where id in (
<foreach collection="ids" item="id" separator=",">
#{id}
</foreach>
)
</delete>
<!-- 第二种批量删除的写法 -->
<!-- open表示该语句以什么开始,close表示以什么结束 -->
<delete id="">
delete from t_user where id in
<foreach collection="ids" item="id" separator="," open="(" close=")">
#{id}
</foreach>
</delete>
mapper:
int batchDeleteUser(int[] ids);
(3)mybatis批量查询
mapper.xml:
<select id="getPostionListIdsByRoleCode" resultType="com.xxx.bean.ElPositionInfo" parameterType="java.util.List">
select
<include refid="Base_Column_List" />
from el_position_info
where roleCode in
<foreach collection="list" item="item" index="index" open="(" close=")" separator=",">
#{item.roleCode}
</foreach>
</select>
mapper:
List<ElPositionInfo> getPostionListIdsByRoleCode(List<ElPositionInfo> list);
(4)mybatis批量修改
mybatis批量修改 (update的值也是动态的)
最近公司有个业务:统计设备app的在线状态,写了个心跳,每分钟获取app的状态,主要是分为:
(1)内网在线
(2)外网在线
(3)第三方网络
(4)离线
放在集合里,然后我在批量修改每个设备的onlineState的标识状态。这就要动态的批量修改onlineState中的值,但是mybatis并不支持 set onlineState = ? 的修改(onlineState是动态的)。然后通过查阅相关资料,通过mysql的case when then 来实现的。具体的实现如下:
mySql Case函数
SELECT SUM(population),
CASE country
WHEN '中国' THEN '亚洲'
WHEN '印度' THEN '亚洲'
WHEN '日本' THEN '亚洲'
WHEN '美国' THEN '北美洲'
WHEN '加拿大' THEN '北美洲'
WHEN '墨西哥' THEN '北美洲'
ELSE '其他' END
FROM Table_A
动态批量修改:DeviceMapper.xml
<!-- 批量修改设备在线状态 -->
<update id="updateBatchOnlineState" parameterType="java.util.List">
update t_device
set online_state = case device_no
<foreach collection="list" item="item">
WHEN #{item.deviceNo} THEN #{item.onlineState}
</foreach>
END
where
device_no in
<foreach collection="list" open="(" separator="," close=")" item="device">
#{device.deviceNo}
</foreach>
</update>
动态批量修改:DeviceMapper.java
int updateBatchOnlineState(List<Device> list);
控制层(xxxxController)
//在线设备编号 前端300秒调用一次 ,服务端640秒认为过期
List<String> deviceNos = DeviceCache.getDeviceNo(640);
List<Device> list = new ArrayList<Device>();
if (CollectionUtils.isNotEmpty(deviceNos)) {
for (String str : deviceNos) {
Device device = new Device();
int indexOf = str.lastIndexOf("-");
String deviceNo = str.substring(0, indexOf);
String type = str.substring(indexOf+1, str.length());
device.setDeviceNo(deviceNo);
device.setOnlineState(Integer.valueOf(type));
list.add(device);
}
int row = deviceService.updateBatchOnlineState(list);
if (row < 1) {
logger.debug("批量修改失败!");
} else {
logger.debug("批量修改成功,已实时获取设备在线状态!");
}
} else {
logger.debug("目前没有设备在线!");
deviceService.modifyAllNotOnline();
}
来源:https://blog.csdn.net/xuforeverlove/article/details/80743625


猜你喜欢
- 前言最近遇到想要实现三指滑动监听的需求,实现代码不方便贴出来,但是思路还是可以记录一下。Muilti-touch 双指缩放探索首先要实现On
- java多线程的同步方法实例代码先看一个段有关银行存钱的代码:class Bank { private int su
- properties配置文件如下:human.name=Mr.Yuhuman.age=21human.gender=male如何把prope
- Result也是Struts2比较重要的一部分,在Result的配置中常用的有四种类型:dispatcher、redirect、chain和
- android中的下拉菜单联动应用非常普遍,android中的下拉菜单用Spinner就能实现,以下列子通过简单的代码实现 * 菜单联动。一
- 在本篇介绍的Winform界面样式改变及存储操作中,是指基于DevExpress进行界面样式的变化。一般情况下,默认我们会为客户提供多种De
- Android不同层次的触摸事件监听 APP开发中,经常会遇到有关手势处理的操作
- 简介MapStruct 是一个代码生成器(可以生成对象映射转换的代码),它基于约定优于配置的方法,极大地简化了 Java bean 类型之间
- 一、项目简述功能包括: 分为管理员及普通业主角色,业主信息,社区房屋,维护 管理,社区车辆,社区投诉,社区缴费,社区业务信息维 护等等功能。
- 实现效果:列出某个目录下的特定后缀名文件(如,列出D盘根目录下txt后缀的文件)import java.io.File;import jav
- 本文将介绍如何在spring boot中集成ehcache作为hibernate的二级缓存。各个框架版本如下spring boot:1.4.
- 目录前言connectTimeout:callTimeout:pingIntervalwriteTimeoutreadTimeout总结前言
- 正常情况下,每个子线程完成各自的任务就可以结束了。不过有的时候,我们希望多个线程协同工作来完成某个任务,这时就涉及到了线程间通信了。本文涉及
- 长久以来统领javaee领域的脚手架以spring struts2 mybatis/hib
- 用idea编写代码不多天,写代码的时候突然左侧目录没了,遇到这种情况相信大多数的小伙伴都是和我一样直接百度,于是网上找了很长时间,大多数都是
- 在业务开发过程中我们会遇到形形色色的注解,但是框架自有的注解并不是总能满足复杂的业务需求,我们可以自定义注解来满足我们的需求。根据注解使用的
- 基本哪些属于引用类型类(object,string),接口、数组、委托引用类型分配在哪里引用类型变量位于线程栈。引用类型实例分配在托管堆上。
- 前言图文并茂的内容往往让人看起来更加舒服,如果只是文字内容的累加,往往会使读者产生视觉疲劳。搭配精美的文章配图则会使文章内容更加丰富,增加文
- 本文为大家分享了Android AIDL实现两个APP间的跨进程通信实例,供大家参考,具体内容如下1 Service端创建首先需要创建一个A
- Arrays 类提供了一个 fill() 方法,可以在指定位置进行数值填充。fill() 方法虽然可以填充数组,但是它的功能有限制,只能使用