mybatis批量新增、刪除、查詢和修改方式
每次寫批量的時候,都要在網(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(); }
以上為個人經(jīng)驗,希望能給大家一個參考,也希望大家多多支持腳本之家。
相關(guān)文章
Java8 Supplier接口和Consumer接口原理解析
這篇文章主要介紹了Java8 Supplier接口和Consumer接口原理解析,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友可以參考下2020-04-04MyBatisPlus報錯:Failed to process,please exclud
這篇文章主要介紹了MyBatisPlus報錯:Failed to process,please exclude the tableName or statementId問題,具有很好的參考價值,希望對大家有所幫助,如有錯誤或未考慮完全的地方,望不吝賜教2024-08-08基于java查找并打印輸出字符串中字符出現(xiàn)次數(shù)
這篇文章主要介紹了基于java查找并打印輸出字符串中字符出現(xiàn)次數(shù),文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友可以參考下2020-11-11java.lang.NumberFormatException異常解決方案詳解
這篇文章主要介紹了java.lang.NumberFormatException異常解決方案詳解,本篇文章通過簡要的案例,講解了該項技術(shù)的了解與使用,以下就是詳細(xì)內(nèi)容,需要的朋友可以參考下2021-08-08SpringBoot+hutool實現(xiàn)圖片驗證碼
本文主要介紹了SpringBoot+hutool實現(xiàn)圖片驗證碼,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2022-08-08Springboot基礎(chǔ)學(xué)習(xí)之初識SpringBoot
今天帶大家學(xué)習(xí)Springboot基礎(chǔ)知識,文中有非常詳細(xì)的圖文解說及代碼示例,對正在學(xué)習(xí)java基礎(chǔ)的小伙伴們很有幫助,需要的朋友可以參考下2021-05-05詳解SpringBoot通過restTemplate實現(xiàn)消費服務(wù)
本篇文章主要介紹了詳解使用RestTemplate消費spring boot的Restful服務(wù),小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2018-01-01