如何理解mybatis批量新增、删除、查询和修改方式

发布时间:2021-09-30 14:46:39 作者:iii
来源:亿速云 阅读:127

本篇内容主要讲解“如何理解mybatis批量新增、删除、查询和修改方式”,感兴趣的朋友不妨来看看。本文介绍的方法操作简单快捷,实用性强。下面就让小编来带大家学习“如何理解mybatis批量新增、删除、查询和修改方式”吧!

目录

每次写批量的时候,都要在网上搜索一下,虽然都做过多次了,但具体的自己还是记不住(汗颜),所以索性今天就记录下来。

前期说明:

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();
  }

到此,相信大家对“如何理解mybatis批量新增、删除、查询和修改方式”有了更深的了解,不妨来实际操作一番吧!这里是亿速云网站,更多相关内容可以进入相关频道进行查询,关注我们,继续学习!

推荐阅读:
  1. layui中table表格如何实现新增,修改,删除,查询,双击获取行数据方式
  2. Mybatis如何批量插入更新xml方式和注解方式

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

mybatis

上一篇:比较实用的JavaScript 片段有哪些

下一篇:如何利用Java写一个学生管理系统

相关阅读

您好,登录后才能下订单哦!

密码登录
登录注册
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》