千家信息网

Mongodb用String自定义ID

发表于:2025-02-03 作者:千家信息网编辑
千家信息网最后更新 2025年02月03日,本篇内容主要讲解"Mongodb用String自定义ID",感兴趣的朋友不妨来看看。本文介绍的方法操作简单快捷,实用性强。下面就让小编来带大家学习"Mongodb用String自定义ID"吧!impo
千家信息网最后更新 2025年02月03日Mongodb用String自定义ID

本篇内容主要讲解"Mongodb用String自定义ID",感兴趣的朋友不妨来看看。本文介绍的方法操作简单快捷,实用性强。下面就让小编来带大家学习"Mongodb用String自定义ID"吧!

import org.bson.Document;import org.bson.types.ObjectId;import org.springframework.data.mongodb.core.mapping.event.AbstractMongoEventListener;import org.springframework.data.mongodb.core.mapping.event.BeforeConvertEvent;import org.springframework.data.mongodb.core.mapping.event.BeforeSaveEvent;import org.springframework.stereotype.Component;@Componentpublic class BeforeConvertListener extends AbstractMongoEventListener {    @Override    public void onBeforeSave(BeforeSaveEvent event) {        Document d = event.getDocument();        if(d==null){  //不太可能            return;        }        Object _id = d.get("_id");        if (_id == null) {            event.getDocument().put("_id", new ObjectId().toString());        } else if (_id instanceof ObjectId) {            event.getDocument().put("_id", _id.toString());        }    }}

通过监听器 , 保存的时候,把 ObjectId 类型的id都转成 Stirng, 如果是空的,就自己加一个String类型的id.

But 有一个问题, 查询,或者删除的时候, 如果String 字符串是一个合法的 ObjectId 的形式。 Spring Data Mongo 会自动转成 ObjectId 去查询或删除。

这样就找不到记录了。

https://stackoverflow.com/questions/14329175/prevent-spring-data-for-mongo-to-convert-ids-to-objectid

这里介绍的一个方式是 抛异常, 还没试过。 看着抛异常就不太想用。

public class CustomMongoConverter extends MappingMongoConverter {    public CustomMongoConverter(MongoDbFactory mongoDbFactory, MappingContext, MongoPersistentProperty> mappingContext) {        super(mongoDbFactory, mappingContext);        conversionService.addConverter(new Converter() {            @Override            public ObjectId convert(String source) {                throw new RuntimeException();            }        });    }}

还没结束, 估计要放弃的节奏,就用 ObjectId 当主键。

import cn.hutool.core.lang.UUID;import cn.hutool.core.util.StrUtil;import org.bson.Document;        import org.bson.types.ObjectId;        import org.springframework.data.mongodb.core.mapping.event.AbstractMongoEventListener;        import org.springframework.data.mongodb.core.mapping.event.BeforeConvertEvent;        import org.springframework.data.mongodb.core.mapping.event.BeforeSaveEvent;        import org.springframework.stereotype.Component;@Componentpublic class BeforeConvertListener extends AbstractMongoEventListener {    @Override    public void onBeforeSave(BeforeSaveEvent event) {        Document d = event.getDocument();        if(d==null){  //不太可能            return;        }        Object _id = d.get("_id");        if (_id == null) {            event.getDocument().put("_id", UUID.fastUUID().toString()/*StrUtil.reverse(new ObjectId().toString())*/);        } else if (_id instanceof ObjectId) {            event.getDocument().put("_id",  UUID.fastUUID().toString()/* StrUtil.reverse(_id.toString())*/);        }    }}

之前一个项目用了 ObjectId ,感觉没啥用。 还容易出错。 比如前台传的String, 查询的时候忘记转为 ObjectId了...

最后,反正是不用 ObjectId了, 只要 String 不符合 ObjectId spring 就不会自动转换, 建议就用 UUID字符串 替代。这样查询删除也没问题。

或者加一个字符串,改变长度就行。

 Object _id = d.get("_id");        if (_id == null) {            event.getDocument().put("_id", new ObjectId().toString()+"c");        } else if (_id instanceof ObjectId) {            event.getDocument().put("_id",  _id.toString()+"c");        }

debug看一下, 他这个转换的判断逻辑是啥,

判断逻辑就是是不是合法的 ObjectId.

到此,相信大家对"Mongodb用String自定义ID"有了更深的了解,不妨来实际操作一番吧!这里是网站,更多相关内容可以进入相关频道进行查询,关注我们,继续学习!

0