溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務(wù)條款》

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

發(fā)布時間:2021-09-30 14:46:39 來源:億速云 閱讀:127 作者:iii 欄目:開發(fā)技術(shù)

本篇內(nèi)容主要講解“如何理解mybatis批量新增、刪除、查詢和修改方式”,感興趣的朋友不妨來看看。本文介紹的方法操作簡單快捷,實用性強。下面就讓小編來帶大家學(xué)習(xí)“如何理解mybatis批量新增、刪除、查詢和修改方式”吧!

目錄
  • 前期說明:

    • 主要有一下3種情況:

  • (1)mybatis批量新增

    • (2)mybatis批量刪除

      • (3)mybatis批量查詢

        • (4)mybatis批量修改

          • mySql Case函數(shù)

          • 動態(tài)批量修改:DeviceMapper.xml

          • 動態(tài)批量修改:DeviceMapper.java

          • 控制層(xxxxController)

        每次寫批量的時候,都要在網(wǎng)上搜索一下,雖然都做過多次了,但具體的自己還是記不?。ê诡仯运餍越裉炀陀涗浵聛?。

        前期說明:

        foreach的主要用在構(gòu)建in條件中,它可以在SQL語句中進(jìn)行迭代一個集合。foreach元素的屬性主要有 item,index,collection,open,separator,close。

        item表示集合中每一個元素進(jìn)行迭代時的別名,index指 定一個名字,用于表示在迭代過程中,每次迭代到的位置,open表示該語句以什么開始,separator表示在每次進(jìn)行迭代之間以什么符號作為分隔 符,close表示以什么結(jié)束,在使用foreach的時候最關(guān)鍵的也是最容易出錯的就是collection屬性,該屬性是必須指定的,但是在不同情況 下,該屬性的值是不一樣的

        主要有一下3種情況:

        1.如果傳入的是單參數(shù)且參數(shù)類型是一個List的時候,collection屬性值為list

        2.如果傳入的是單參數(shù)且參數(shù)類型是一個array數(shù)組的時候,collection的屬性值為array

        3.如果傳入的參數(shù)是多個的時候,我們就需要把它們封裝成一個Map了,當(dāng)然單參數(shù)也可以封裝成map,實際上如果你在傳入?yún)?shù)的時候,在breast里面也是會把它封裝成一個Map的,map的key就是參數(shù)名,所以這個時候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實現(xiàn)類:
        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)) {
                                    //以用戶手機號碼為唯一標(biāo)示,批量修改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表示以什么結(jié)束 -->
        <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的值也是動態(tài)的)

        最近公司有個業(yè)務(wù):統(tǒng)計設(shè)備app的在線狀態(tài),寫了個心跳,每分鐘獲取app的狀態(tài),主要是分為:

        (1)內(nèi)網(wǎng)在線

        (2)外網(wǎng)在線

        (3)第三方網(wǎng)絡(luò)

        (4)離線

        放在集合里,然后我在批量修改每個設(shè)備的onlineState的標(biāo)識狀態(tài)。這就要動態(tài)的批量修改onlineState中的值,但是mybatis并不支持 set onlineState = ? 的修改(onlineState是動態(tài)的)。然后通過查閱相關(guān)資料,通過mysql的case when then 來實現(xiàn)的。具體的實現(xiàn)如下:

        mySql Case函數(shù)

        SELECT  SUM(population), 
                CASE country 
                        WHEN '中國'     THEN '亞洲' 
                        WHEN '印度'     THEN '亞洲' 
                        WHEN '日本'     THEN '亞洲' 
                        WHEN '美國'     THEN '北美洲' 
                        WHEN '加拿大'  THEN '北美洲' 
                        WHEN '墨西哥'  THEN '北美洲' 
                ELSE '其他' END 
        FROM    Table_A

        動態(tài)批量修改:DeviceMapper.xml

        <!-- 批量修改設(shè)備在線狀態(tài) -->
           <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>

        動態(tài)批量修改:DeviceMapper.java

        int updateBatchOnlineState(List<Device> list);

        控制層(xxxxController)

        //在線設(shè)備編號  前端300秒調(diào)用一次 ,服務(wù)端640秒認(rèn)為過期
          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("批量修改成功,已實時獲取設(shè)備在線狀態(tài)!");
           }
          } else {
           logger.debug("目前沒有設(shè)備在線!");
           deviceService.modifyAllNotOnline();
          }

        到此,相信大家對“如何理解mybatis批量新增、刪除、查詢和修改方式”有了更深的了解,不妨來實際操作一番吧!這里是億速云網(wǎng)站,更多相關(guān)內(nèi)容可以進(jìn)入相關(guān)頻道進(jìn)行查詢,關(guān)注我們,繼續(xù)學(xué)習(xí)!

        向AI問一下細(xì)節(jié)

        免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報,并提供相關(guān)證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權(quán)內(nèi)容。

        AI