温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

Mongodb用String自定义ID

发布时间:2021-06-22 14:38:26 来源:亿速云 阅读:447 作者:chen 栏目:大数据

本篇内容主要讲解“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;

@Component
public class BeforeConvertListener extends AbstractMongoEventListener<Object> {
    @Override
    public void onBeforeSave(BeforeSaveEvent<Object> 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<? extends MongoPersistentEntity<?>, MongoPersistentProperty> mappingContext) {
        super(mongoDbFactory, mappingContext);
        conversionService.addConverter(new Converter<String, ObjectId>() {
            @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;

@Component
public class BeforeConvertListener extends AbstractMongoEventListener<Object> {
    @Override
    public void onBeforeSave(BeforeSaveEvent<Object> 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

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

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI