MongoDB学习-->设置通用的自增ID替代ObjectId

插入mongodb数据时,会为其分配一个随机id,想要设置通用的自增id,可以进行以下操作

1.创建自增序列

 1 package com.tangzhe.autoid;
 2 
 3 import lombok.Data;
 4 import org.springframework.data.annotation.Id;
 5 import org.springframework.data.mongodb.core.mapping.Document;
 6 import org.springframework.data.mongodb.core.mapping.Field;
 7 
 8 /**
 9  * Created by 唐哲
10  * 2018-03-14 21:26
11  * 自增序列
12  */
13 @Document(collection = "sequence")
14 @Data
15 public class Sequence {
16 
17     @Id
18     private String id; //序列的id
19 
20     @Field("coll_name")
21     private String collName; //coll的name
22 
23     @Field("seq_id")
24     private Long seqId; //coll的id,自增id
25 
26 }

2.创建AutoId注解

 1 package com.tangzhe.autoid;
 2 
 3 import java.lang.annotation.ElementType;
 4 import java.lang.annotation.Retention;
 5 import java.lang.annotation.RetentionPolicy;
 6 import java.lang.annotation.Target;
 7 
 8 /**
 9  * Created by 唐哲
10  * 2018-03-14 21:55
11  */
12 @Retention(RetentionPolicy.RUNTIME)
13 @Target({ElementType.FIELD})
14 public @interface AutoId {
15 }

3.创建需要使用自增ID的实体类

 1 package com.tangzhe.autoid;
 2 
 3 import lombok.Data;
 4 import org.springframework.data.mongodb.core.mapping.Document;
 5 import org.springframework.data.mongodb.core.mapping.Field;
 6 
 7 /**
 8  * Created by 唐哲
 9  * 2018-03-14 21:56
10  */
11 @Document(collection = "stu_info")
12 @Data
13 public class StuInfo {
14 
15     @AutoId
16     private Long id;
17 
18     @Field("name")
19     private String name;
20 
21 }

4.自增id监听器

 1 package com.tangzhe.autoid;
 2 
 3 import java.lang.reflect.Field;
 4 import org.springframework.beans.factory.annotation.Autowired;
 5 import org.springframework.data.mongodb.core.FindAndModifyOptions;
 6 import org.springframework.data.mongodb.core.MongoTemplate;
 7 import org.springframework.data.mongodb.core.mapping.Document;
 8 import org.springframework.data.mongodb.core.mapping.event.AbstractMongoEventListener;
 9 import org.springframework.data.mongodb.core.mapping.event.BeforeConvertEvent;
10 import org.springframework.data.mongodb.core.query.Criteria;
11 import org.springframework.data.mongodb.core.query.Query;
12 import org.springframework.data.mongodb.core.query.Update;
13 import org.springframework.util.ReflectionUtils;
14 import org.springframework.util.ReflectionUtils.FieldCallback;
15 
16 /**
17  * 自增id监听器
18  */
19 public class SaveMongoEventListener extends AbstractMongoEventListener<Object> {
20     
21     @Autowired
22     private MongoTemplate mongoTemplate;
23     
24     @Override
25     public void onBeforeConvert(BeforeConvertEvent<Object> event) {
26         if (event != null && event.getSource() != null) {
27             ReflectionUtils.doWithFields(event.getSource().getClass(), new FieldCallback() {
28                 
29                 @Override
30                 public void doWith(Field field) throws IllegalArgumentException, IllegalAccessException {
31                     if (field.isAnnotationPresent(AutoId.class)) {
32                         String collName = event.getSource().getClass().getSimpleName();
33                         if (event.getSource().getClass().isAnnotationPresent(Document.class)) {
34                             collName = event.getSource().getClass().getAnnotation(Document.class).collection();
35                         }
36                         field.set(event.getSource(), getNextId(collName));
37                     }
38                 }
39                 
40             });
41         }
42     }
43     
44     public Long getNextId(String collName) {
45         Query query = Query.query(Criteria.where("collName").is(collName));
46         Update update = new Update().inc("seqId", 1);
47         FindAndModifyOptions options = FindAndModifyOptions.options().upsert(true).returnNew(true);
48         return mongoTemplate.findAndModify(query, update, options, Sequence.class).getSeqId();
49     }
50 
51 }

5.测试自增ID

 1 package com.tangzhe.autoid;
 2 
 3 import com.mongodb.BasicDBObject;
 4 import org.junit.Test;
 5 import org.junit.runner.RunWith;
 6 import org.springframework.beans.factory.annotation.Autowired;
 7 import org.springframework.boot.test.context.SpringBootTest;
 8 import org.springframework.data.mongodb.core.FindAndModifyOptions;
 9 import org.springframework.data.mongodb.core.MongoTemplate;
10 import org.springframework.data.mongodb.core.query.Criteria;
11 import org.springframework.data.mongodb.core.query.Query;
12 import org.springframework.data.mongodb.core.query.Update;
13 import org.springframework.test.context.junit4.SpringRunner;
14 
15 /**
16  * Created by 唐哲
17  * 2018-03-14 21:29
18  * 自增id测试
19  */
20 @RunWith(SpringRunner.class)
21 @SpringBootTest
22 public class AutoIdTest {
23 
24     @Autowired
25     private MongoTemplate mongoTemplate;
26 
27     //@Test
28     public void testAutoId() {
29         Query query = Query.query(Criteria.where("collName").is("stu_info"));
30         Update update = new Update().inc("seqId", 1);
31         FindAndModifyOptions options = FindAndModifyOptions.options().upsert(true).returnNew(true);
32         Long stuInfoId = mongoTemplate.findAndModify(query, update, options, Sequence.class).getSeqId();
33 
34         mongoTemplate.getCollection("stu_info").save(new BasicDBObject("_id", stuInfoId).append("name", "zhangsan"));
35     }
36 
37     /**
38      * 测试自增id监听器
39      */
40     //@Test
41     public void testSaveMongoEventListener() {
42         StuInfo stuInfo = new StuInfo();
43         stuInfo.setName("lisi");
44         mongoTemplate.save(stuInfo);
45     }
46 
47 }
原文地址:https://www.cnblogs.com/tangzhe/p/8599486.html