MongoDB自增id的使用

今年的第一篇文章,首先祝大家新年快乐🎈🎈🎈然后前段时间在做项目的时候用mongodb来做数据库,遇到了一些问题,就是主键没法像mysql一样那么方便的自增,于是在网络上找了一些方法,并增加了一条判断

1.首先我们需要先加一个注解:
将@AutoIncKey注解添加到需要自增的实体类的id上

2.创建一个注解类: AutoIncKey.class

/**
 *自定义的注解类
 */
@Target(ElementType.FIELD)
@Retention(RetentionPolicy.RUNTIME)
public @interface AutoIncKey {}

3.创建一个序列信息类: SeqInfo.class

/**
 * 序列信息类
 */
@Data
public class SeqInfo {
        String id;
        String collName;
        Integer value;
}

4.最后附上修改后的工具类代码: SaveEventListener.class

/**
 * 监听添加操作,并将自增id插入
 */
@Component
public class SaveEventListener<T> extends AbstractMongoEventListener<Object> {

    private static final Logger logger = LoggerFactory.getLogger(SaveEventListener.class);
    @Autowired
    private MongoTemplate mongo;

    @Override
    public void onBeforeConvert(BeforeConvertEvent<Object> event) {
        logger.info(event.getSource().toString());
        T source = (T) event.getSource();
        if (source != null) {
            ReflectionUtils.doWithFields(source.getClass(), new ReflectionUtils.FieldCallback() {
                public void doWith(Field field) throws IllegalArgumentException, IllegalAccessException {
                    ReflectionUtils.makeAccessible(field);
                    // 如果字段添加了我们自定义的AutoIncKey注解
                    if (field.isAnnotationPresent(AutoIncKey.class)) {
                        // 设置自增ID
                        try {
                            // 判断添加了自增注解的当前对象的id是否未空,不为空时不自动生成id
                            if (source.getClass().getDeclaredField(field.getName())==null){
                                field.set(source, getNextId(source.getClass().getSimpleName()));
                            }
                        } catch (NoSuchFieldException e) {
                            e.printStackTrace();
                        }
                    }
                }
            });
        }

    }

    private String getNextId(String collName) {
        Query query = new Query(Criteria.where("collName").is(collName));
        Update update = new Update();
        update.inc("value", 1);
        FindAndModifyOptions options = new FindAndModifyOptions();
        options.upsert(true);
        options.returnNew(true);
        SeqInfo seqInfo = mongo.findAndModify(query, update, options, SeqInfo.class);
        return seqInfo.getValue() + ""; //可以根据需求拼接自己的格式
    }
}

这样就可以直接愉快的使用自增主键了,本篇代码来源与9个月前…历史悠久,最近刚想起来这个问题,感谢关注,最近会持续更新,之前项目一直在忙,感谢关注.
如有问题,欢迎留言指出,谢谢

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值