springboot 整合 mongodb實現 批量更新數據

現需求:需要批量將1000個數據先查詢在更新到mongodb(如果查詢不到數據,則添加數據)

1:工具類BathUpdateOptions

 1 import org.springframework.data.mongodb.core.query.Query;
 2 import org.springframework.data.mongodb.core.query.Update;
 3 
 4 public class BathUpdateOptions {
 5     
 6     private Query query;
 7     private Update update;
 8     private boolean upsert = true;
 9     private boolean multi = false;
10 
11     public Query getQuery() {
12         return query;
13     }
14 
15     public void setQuery(Query query) {
16         this.query = query;
17     }
18 
19     public Update getUpdate() {
20         return update;
21     }
22 
23     public void setUpdate(Update update) {
24         this.update = update;
25     }
26 
27     public boolean isUpsert() {
28         return upsert;
29     }
30 
31     public void setUpsert(boolean upsert) {
32         this.upsert = upsert;
33     }
34 
35     public boolean isMulti() {
36         return multi;
37     }
38 
39     public void setMulti(boolean multi) {
40         this.multi = multi;
41     }
42 
43 }

2:需要更新的domain

 1 @Document(collection = "video_show_view")
 2 public class VideoShowView {
 3     //唯一值
 4     private String id;
 5     //節目id
 6     private String cid;
 7     //app播放次數
 8     private String view;
 9     //app虛擬播放次數
10     private String virtualViews;
11     //最后更新時間 時間戳
12     private String updateTime;
13   //get set ......
14 }

3:獲取BathUpdateOptions 集合

/*** @author xuyou* @Package com.migu.live.mao* @Description:* @date 2018/6/11 16:13*/
@Repository
public class VideoShowViewMao {@Autowiredprivate MongoTemplate mongoTemplate;public BathUpdateOptions getBathUpdateOptions(VideoShowView videoShowView){BathUpdateOptions options = new BathUpdateOptions();Query query = new Query();//查詢條件query.addCriteria(Criteria.where("cid").is(videoShowView.getCid()));query.addCriteria(Criteria.where("types").is(videoShowView.getTypes()));options.setQuery(query);//mongodb 默認是false,只更新找到的第一條記錄,如果這個參數為true,就把按條件查出來多條記錄全部更新。options.setMulti(true);Update update = new Update();//更新內容update.set("view", videoShowView.getView());update.set("updateTime", videoShowView.getUpdateTime());options.setUpdate(update);return options;}public void bathUpdate(List<BathUpdateOptions> bups){BathUpdateUtil.bathUpdate(mongoTemplate, VideoShowView.class, bups);}
}

4:操作mongodb的工具類BathUpdateUtil

 1 import java.util.ArrayList;
 2 import java.util.List;
 3 
 4 import org.springframework.dao.InvalidDataAccessApiUsageException;
 5 import org.springframework.data.mongodb.core.MongoTemplate;
 6 import org.springframework.data.mongodb.core.mapping.Document;
 7 
 8 import com.migu.live.data.BathUpdateOptions;
 9 import com.mongodb.BasicDBObject;
10 import com.mongodb.CommandResult;
11 import com.mongodb.DBCollection;
12 import com.mongodb.DBObject;
13 
14 public class BathUpdateUtil {
15 
16     /**
17      * @description:批量更新mongodb數據
18      * @author: xuyou
19      * @date: 2018年8月14日 上午11:28:29 
20      */
21     public static int bathUpdate(MongoTemplate mongoTemplate, Class<?> entityClass, 
22         List<BathUpdateOptions> options) {
23         String collectionName = determineCollectionName(entityClass);
24         return doBathUpdate(mongoTemplate.getCollection(collectionName), 
25              collectionName, options, true);
26     }
27     
28     private static String determineCollectionName(Class<?> entityClass) {
29         if (entityClass == null) {
30             throw new InvalidDataAccessApiUsageException(
31                     "No class parameter provided, entity collection can't be determined!");
32         }
33         String collName = entityClass.getSimpleName();
34         if(entityClass.isAnnotationPresent(Document.class)) {
35             Document document = entityClass.getAnnotation(Document.class);
36             collName = document.collection();
37         } else {
38             collName = collName.replaceFirst(collName.substring(0, 1)
39                       ,collName.substring(0, 1).toLowerCase()) ;
40         }
41         return collName;
42     }
43 
44     private static int doBathUpdate(DBCollection dbCollection, String collName,         
45                        List<BathUpdateOptions> options, boolean ordered) {
46         DBObject command = new BasicDBObject();
47         command.put("update", collName);
48         List<BasicDBObject> updateList = new ArrayList<BasicDBObject>();
49         for (BathUpdateOptions option : options) {
50             BasicDBObject update = new BasicDBObject();
51             update.put("q", option.getQuery().getQueryObject());
52             update.put("u", option.getUpdate().getUpdateObject());
53             update.put("upsert", option.isUpsert());
54             update.put("multi", option.isMulti());
55             updateList.add(update);
56         }
57         command.put("updates", updateList);
58         command.put("ordered", ordered);
59         CommandResult commandResult = dbCollection.getDB().command(command);
60         return Integer.parseInt(commandResult.get("n").toString());
61     }
62 }

5:業務代碼? 可根據實際需求 進行修改

 1 /**
 2      * @description:執行更新
 3      * @param liveKeys 需要更新的集合
 4      * @return void     
 5      * @author: xuyou
 6      * @date: 2018年8月14日 上午11:44:06 
 7      * @throws
 8      */
 9     public void bathUpdateMongoDB (Set<String> liveKeys){
10         //將直播播放次數入mongoDB
11         List<BathUpdateOptions> bupsList = new ArrayList<BathUpdateOptions>();
12         for (String id : liveKeys) {
13             VideoShowView videoShowView = new VideoShowView();
14             //設置一些更新條件 此處省略
15             videoShowView.setUpdateTime(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
16             BathUpdateOptions options = videoShowViewMao.getBathUpdateOptions(videoShowView);
17             bupsList.add(options);
18             if(bupsList.size() >= 1000){
19                 logger.info("bupsList : {}",bupsList.size());
20                 videoShowViewMao.bathUpdate(bupsList);
21                 bupsList = new ArrayList<BathUpdateOptions>();
22             }
23         }
24         //TODO 更新liveList剩余少于1000的數據
25         logger.info("bupsList : {}",bupsList.size());
26         if (bupsList != null && bupsList.size() > 0) {
27             videoShowViewMao.bathUpdate(bupsList);
28         }
29     }

6;pom文件

1     <!-- 對mongodb的支持 -->
2         <dependency>
3             <groupId>org.springframework.boot</groupId>
4             <artifactId>spring-boot-starter-data-mongodb</artifactId>
5             <version>2.0.2.RELEASE</version>
6         </dependency>

7:配置

spring.data.mongodb.uri=mongodb://10.200.85.97:27017,10.200.85.98:27017,10.200.85.99:27017/data_consumer

?

轉載于:https://www.cnblogs.com/xuyou551/p/9473713.html

本文來自互聯網用戶投稿,該文觀點僅代表作者本人,不代表本站立場。本站僅提供信息存儲空間服務,不擁有所有權,不承擔相關法律責任。
如若轉載,請注明出處:http://www.pswp.cn/news/450922.shtml
繁體地址,請注明出處:http://hk.pswp.cn/news/450922.shtml
英文地址,請注明出處:http://en.pswp.cn/news/450922.shtml

如若內容造成侵權/違法違規/事實不符,請聯系多彩編程網進行投訴反饋email:809451989@qq.com,一經查實,立即刪除!

相關文章

【開題報告】基于微信小程序的校園資訊平臺的設計與實現

1.選題背景與意義 隨著移動互聯網的快速發展&#xff0c;微信成為了人們日常生活中不可或缺的工具之一。在校園生活中&#xff0c;學生們對于校園資訊的獲取和交流需求也越來越高。然而&#xff0c;傳統的校園資訊發布方式存在信息不及時、傳播范圍有限等問題&#xff0c;無法…

三種Cache寫入方式原理簡介

三種Cache寫入方式原理簡介 在386以上檔次的微機中&#xff0c;為了提高系統效率&#xff0c;普遍采用Cache&#xff08;高速緩沖存儲器&#xff09;&#xff0c;現在的系統甚至可以擁有多級Cache。Cache實際上是位于CPU與DRAM主存儲器之間少量超高速的靜態存儲器&#xff08;S…

Minor GC和Full GC

我們在日常開發中可能經常會聽大家談論GC&#xff0c;但是其實很多人對GC的種類其實并不是很了解&#xff0c;接下來我們簡單介紹下Minor GC和Full GC及他們的區別。 MinorGC&#xff1a; 也可以叫作新生代GC&#xff0c;指的是發生在新生代的垃圾收集動作。因為新生代中對象大…

linux安裝軟件的幾種方法

見&#xff1a;http://blog.csdn.net/u010509774/article/details/50593231 一、rpm包安裝方式步驟&#xff1a; 1、找到相應的軟件包&#xff0c;比如soft.version.rpm&#xff0c;下載到本機某個目錄&#xff1b; 2、打開一個終端&#xff0c;su -成root用戶&#xff1b; …

Android NDK MediaCodec在ijkplayer中的實踐

https://www.jianshu.com/p/41d3147a5e07 從API 21&#xff08;Android 5.0&#xff09;開始Android提供C層的NDK MediaCodec的接口。 Java MediaCodec是對NDK MediaCodec的封裝&#xff0c;ijkplayer硬解通路一直使用的是Java MediaCodec接Surface的方式。 本文的主要內容是&a…

leetcode-49-字母異位詞分組(神奇的哈希)

題目描述&#xff1a; 給定一個字符串數組&#xff0c;將字母異位詞組合在一起。字母異位詞指字母相同&#xff0c;但排列不同的字符串。 示例: 輸入: ["eat", "tea", "tan", "ate", "nat", "bat"], 輸出: [[&quo…

【精心總結】java內存模型和多線程必會知識

內存模型 &#xff08;1&#xff09;java內存模型到底是個啥子東西&#xff1f; java內存模型是java虛擬機規范定義的一種特定模型&#xff0c;用以屏蔽不同硬件和操作系統的內存訪問差異&#xff0c;讓java在不同平臺中能達到一致的內存訪問效果&#xff0c;是在特定的協議下…

工作流 activity 視頻教程 + redis 視頻教程 百度網盤分享地址

前些天發現了一個巨牛的人工智能學習網站&#xff0c;通俗易懂&#xff0c;風趣幽默&#xff0c;忍不住分享一下給大家。點擊跳轉到教程。 云盤下載都沒有密碼&#xff0c;直接下載&#xff0c;解壓有密碼&#xff1a;chongxiangmengxiangjiaoyu&#xff0c; 解壓完成后就可以…

快速解決 GRADLE 項目下載 gradle-*-all.zip 慢的問題

1、首先根據項目中 gradle\wrapper\gradle-wrapper.properties 文件的 distributionUrl 屬性的值 #Tue Feb 06 12:27:20 CET 2018 distributionBaseGRADLE_USER_HOME distributionPathwrapper/dists zipStoreBaseGRADLE_USER_HOME zipStorePathwrapper/dists distributionUrlht…

[Python] 程序結構與控制流

1. 條件語句 if、else與elif語句用于控制條件代碼的執行。條件語句的一般格式如下&#xff1a; if expression:statements elif expression:statements elif expression:statements ... else:statements 如果不需要執行任何操作&#xff0c;可以省略條件語句的else和elif子句。…

webrtc 源碼結構

apiWebRTC 接口層。包括 DataChannel, MediaStream, SDP相關的接口。各瀏覽器都是通過該接口層調用的 WebRTC。call存放的是 WebRTC “呼叫&#xff08;Call&#xff09;” 相關邏輯層的代碼。audio存放音頻網絡邏輯層相關的代碼。音頻數據邏輯上的發送&#xff0c;接收等代碼。…

mysql查詢流程解析及重要知識總結

時光荏苒啊&#xff01;在過兩個月我就工作滿三年了&#xff0c;大學畢業的情景還歷歷在目&#xff0c;而我已經默默的向油膩中年大叔進發了。作為一名苦逼的后端工程師&#xff0c;我搞過一段時間python&#xff0c;現在靠java糊口&#xff0c;但后來才發現&#xff0c;始終不…

界面無小事(八):RecyclerView增刪item

界面無小事(一): RecyclerViewCardView了解一下 界面無小事(二): 讓RecyclerView展示更多不同視圖 界面無小事(三):用RecyclerView Toolbar做個文件選擇器 界面無小事(四):來寫個滾動選擇器吧! 界面無小事(五):自定義TextView 界面無小事(六):來做個好看得側拉菜單! 界面無小事…

Failed to install Tomcat7 service 解決

見&#xff1a; http://blog.csdn.net/desow/article/details/21446197 tomcat 安裝時出現 Failed to install Tomcat7 service 今天在安裝tomcat時提示 Failed to install Tomcat7 service了&#xff0c;花了大半天的時間找到了原因&#xff0c;下面分享給大家&#xff0c;希望…

保守官僚 諾基亞就這樣迷失在智能機時代?

7月19日&#xff0c;諾基亞發布了二季度財報&#xff0c;凈虧損達到了17億美元&#xff0c;其中智能手機份額和銷售量進一步下滑&#xff0c;這個智能手機的領導者&#xff0c;正在因智能手機而急速墜落。諾記亞領先業界近十年就把握住了智能手機的趨勢&#xff0c;并推出了首款…

django集成ansibe實現自動化

動態生成主機列表和相關參數 def create_admin_domain(admin_node):workpath BASE_DIR /tools/ansible/scripthosts_file BASE_DIR /tools/ansible/host/ createhostfile()yml_file BASE_DIR /tools/ansible/yml/ create_admin_domain.ymldomain_path admin_node.doma…

extend 對象繼承

function extend(o, n, override) {for (var p in n) {if (n.hasOwnProperty(p) && (!o.hasOwnProperty(p) || override))o[p] n[p];} }// 默認參數 var options {pageIndex: 1,pageTotal: 2 };// 新設置參數 var userOptions {pageIndex: 3,pageSize: 10 }extend(o…

【spring容器啟動】之bean的實例化和初始化(文末附:spring循環依賴原理)

本次我們通過源碼介紹ApplicationContext容器初始化流程&#xff0c;主要介紹容器內bean的實例化和初始化過程。ApplicationContext是Spring推出的先進Ioc容器&#xff0c;它繼承了舊版本Ioc容器BeanFactory&#xff0c;并進一步擴展了容器的功能&#xff0c;增加了bean的自動識…

如何將自己的Java項目部署到外網

見&#xff1a;http://jingyan.baidu.com/article/90bc8fc864699af653640cf7.html 做b/s模式的web開發不同于c/s模式的客戶端開發&#xff0c;c/s模式我們只要做好生成可執行文件發送給其他人&#xff0c;其他人就可以用了。但是c/s模式不同&#xff0c;在同一局域網下&#xf…

[Swift]LeetCode916.單詞子集 | Word Subsets

★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★?微信公眾號&#xff1a;山青詠芝&#xff08;shanqingyongzhi&#xff09;?博客園地址&#xff1a;山青詠芝&#xff08;https://www.cnblogs.com/strengthen/&#xff09;?GitHub地址&a…