• mongodb添加字段和创建自增主键


    sql类型

    --添加字段
    db.library_category.update({},{$set:{code:""}},{multi:1})
    --添加自增序列集合

    db.getCollection("sequence").drop();
    db.createCollection("sequence");

    //添加字段中的集合
    db.getCollection("sequence").insert([ {
    _id: "code1",
    seqId: 7
    } ]);


    --给添加的字段赋值
    db.getCollection('library_category').find({"code":6}).forEach(
    function(item){
    db.getCollection('library_category').update({"_id":item._id},{$set: {"code":db.sequence.findAndModify({
    query: {_id:"code1" },
    update: {$inc:{seqId:1}},
    new: true
    }).seqId}})
    }
    )

    java 代码

    一.
    创建自定义注解:

    package com.orangecds.designmaterial.api.entity;

    import java.lang.annotation.ElementType;
    import java.lang.annotation.Retention;
    import java.lang.annotation.RetentionPolicy;
    import java.lang.annotation.Target;

    /**
    * @author xiyun.zhao
    * @title: AutoIncKey
    * @projectName design-material
    * @description: 标识注解:标识主键ID需要自动增长
    * @date 2021/8/317:45
    */
    @Target(ElementType.FIELD)
    @Retention(RetentionPolicy.RUNTIME)
    public @interface AutoIncKey {

    }

    二.
    创建自增主键实体类

    package com.orangecds.designmaterial.api.entity;

    import io.swagger.annotations.ApiModel;
    import io.swagger.annotations.ApiModelProperty;
    import lombok.Data;
    import org.springframework.data.mongodb.core.index.Indexed;
    import org.springframework.data.mongodb.core.mapping.Document;

    /**
    * @program: design-material
    * @ClassName SeqInfo
    * @description: 创建自增长序列
    * @author: xiyun.zhao
    * @create: 2021-08-03 17:41
    **/
    @ApiModel("序列的类")
    @Data
    @Document(collection = "sequence")
    public class SeqInfo {
    @ApiModelProperty("逻辑主键Id")
    @Indexed
    private String id;

    @ApiModelProperty("序列值")
    private Long seqId;

    }


    三.
    创建自定义注解监听的类

    package com.orangecds.designmaterial.seque.listener;

    import com.orangecds.designmaterial.api.entity.AutoIncKey;
    import com.orangecds.designmaterial.api.entity.SeqInfo;
    import org.slf4j.Logger;
    import org.slf4j.LoggerFactory;
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.data.mongodb.core.FindAndModifyOptions;
    import org.springframework.data.mongodb.core.MongoTemplate;
    import org.springframework.data.mongodb.core.mapping.event.AbstractMongoEventListener;
    import org.springframework.data.mongodb.core.mapping.event.BeforeConvertEvent;
    import org.springframework.data.mongodb.core.query.Criteria;
    import org.springframework.data.mongodb.core.query.Query;
    import org.springframework.data.mongodb.core.query.Update;
    import org.springframework.stereotype.Component;
    import org.springframework.util.ReflectionUtils;

    import java.lang.reflect.Field;
    /**
    * @description: 实现监听类
    * @author xiyun.zhao
    * @param:
    * @return:
    * @date: 2021/8/4 10:16
    */
    @Component
    public class SaveEventListener extends AbstractMongoEventListener<Object>{
    private static final Logger logger= LoggerFactory.getLogger(SaveEventListener.class);

    修改git 的用户名称:git config --global --replace-all user.name "xiyun.zhao"

    @Autowired
    private MongoTemplate mongo;

    @Override
    public void onBeforeConvert(BeforeConvertEvent<Object> event) {
    final Object source = event.getSource();
    if (source != null) {
    ReflectionUtils.doWithFields(source.getClass(), new ReflectionUtils.FieldCallback() {
    @Override
    public void doWith(Field field) throws IllegalArgumentException, IllegalAccessException {
    ReflectionUtils.makeAccessible(field);
    // 如果字段添加了我们自定义的AutoIncKey注解
    if (field.isAnnotationPresent(AutoIncKey.class)) {
    // 设置自增ID
    field.set(source, getNextId(source.getClass().getSimpleName()));
    }
    }
    });
    }

    }

    private Long getNextId(String id) {
    Query query = new Query(Criteria.where("id").is(id));
    Update update = new Update();
    update.inc("seqId", 1);
    FindAndModifyOptions options = new FindAndModifyOptions();
    options.upsert(true);
    options.returnNew(true);
    SeqInfo seqInfo= mongo.findAndModify(query, update, options, SeqInfo.class);
    return seqInfo.getSeqId();
    }

    }

    假如我的博客对你有用,请你关注我一下,告诉我你来过,你的关注是我前进的动力,希望更多的人记录自己的问题,去帮助别人更是帮助自己避免再次出现这样那样的问题,谢谢你的来过!
  • 相关阅读:
    springMVC(注解版笔记)
    关于在Eclipse里面启动了服务,但是localhost:8080无法访问的问题:
    springmvc基础知识
    private
    hashtable,hashMap,vector和ArrayList
    使用IDEA创建java项目(hello word)
    设计模式
    设计模式(总纲)
    spring-boot集成PageHelper和通用Mapper
    spring-boot集成mybatis
  • 原文地址:https://www.cnblogs.com/zxy-come-on/p/15098900.html
Copyright © 2020-2023  润新知