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

以上為個人經驗,希望能給大傢一個參考,也希望大傢多多支持WalkonNet。

推薦閱讀: