mongoDB如何实现id自增?这篇文章非常值得观看

很多小伙伴想知道mongoDB如何实现id自增,那么今天小编就通过这篇文章来给大家分享一下实现mongoDB  id自增的方法 。感兴趣的小伙伴可以耐心阅读一下这篇文章 。

mongoDB如何实现id自增?这篇文章非常值得观看

文章插图
我们的思路个大概要按照这个思路来走:首先我们需要创建一个用序列计数的文档,用作记录所有文档的名称和序列值,序列值默认设置成0,然后每次进行插入操作的时候,则+1,作为本次操作的id 。
程序实现如下(小编使用的是IDEA+Java8+SpringBoot):
(一)创建序列计数类,用于存储各文档以及文档序列值 。
package com.dfans.entity;import org.springframework.data. annotation.Id;import org.springframework.data.mongodb.core.mapping. Document;import org.springframework.data.mongodb.core.mapping.Field;习/*** 序列计数类**/@Document (collection = "sequence"')public class SeqInfo {/*** 主键*/@Idprivate String id;/*** 集合名称*/@Fieldprivate String collName;/*** 序列值*/@Fieldprivate Long seqId;(二)自定义注解
package com.dfans. common;import java.lang.annotation.Retention;import java.lang.annotation.ElementType;import java.lang.annotation.RetentionPolicy;import java.lang.annotation.Target;/*** 自定义注解,级别设置RUNTIME*/@Target (ElementType.FIELD))aRetention(RetentionPolicy.RUNTIME)public @interface AutoIncKey {}(三)定义实体类(get、set),与文档一一对应
package com.dfans.entity;)import com.dfans. common.AutoIncKey;import org. springframework.data.annotation.Id;import java.io.Serializable;import java.math.BigDecimal;/*** 数据分析-中心库*/public class MidMain implements Serializable{private static final long serialVersionUID=-9137732458189001145L:*** id*/QId@AutoIncKeyprivate java. lang. Long id = OL;/*水* 外键-关联数据id*/private java.lang.Integer fid;*** 数据类别:1新闻、2微博、3自媒体、4股吧、5投资者互动平台、6研报*/private java.lang.Integer category;/*** 话题词库ID,通过该iD与话题词库关联,多个采用’,"分割*private java. lang.String topicId;/stesk* 股票词库ID,通过该ID与股票词库关联,多个采用”,‘分割*/private java. lang.String stockId;/*水* 关注度*/private BigDecimal interested;/水水* 情绪值(四)定义监听类SaveEventListener 。重写save方法 。在每次存储时候进行主键自增
/*** 保存文档监听类<br>* 在保存对象时,通过反射方式为其生成ID*@Componentpublic class SaveEventlistener extends AbstractMongoEventListener<Object> {@Autowiredprivate MongoTemplate mongo;@Overridepublic void onBeforeConvert (BeforeConvertEvent<Object> event) {Object source = event.getSource();if (source != null)ReflectionUtils.doWithfields(source.getClass(), new Reflectienltils. FieldCallbacklinfpublic void doWith(Field field) throws IllegalArgumentException, IllegalAccessException{ReflectionUtils.makeAccessible(field);// 如果字段添加了我们自定义的AutoInckey注解if (field. isAnnotat ionPresent (AutoInckey . class) )// 设置自增IDfield. set (source, getNextId(source.getClass().getSimpleName()));/*** 获取下一个自增ID*@param collName*集合(这里用类名,就唯一性来说最好还是存放长类名) 名称* @return 序列值*/private Long getNextId(String collName) {Query query = new Query(Criteria.where("collName"). is (collName));Update update = new Update() ;update. inc( key:"segId",inc: 1):FindAndModifyOptions options= new FindAndModify0ptions ();options. upsert(true);options.returnNew(true);SeqInfo seq = mongo.findAndModify(query, update, options, SeqInfo.class);return seq.getSeqId();

推荐阅读