简体   繁体   English

mongo-java-driver如何使用字符串ID反射ObjectId

[英]mongo-java-driver how to use string id reflection ObjectId

in mongodb: 在mongodb中:

{ 
"_id" : ObjectId("5a1e8e10cf40cb2b6b08112f")
}

in C#, i can use this (ps:i need to setting string ID,not ObjectID) 在C#中,我可以使用它(ps:我需要设置字符串ID,而不是ObjectID)

[BsonIgnoreExtraElements]
    public class ElapsedTimeLog : IEntity<string>
    {
        /// <summary>
        /// 主键ID
        /// </summary>
        [BsonId]
        [BsonRepresentation(BsonType.ObjectId)]
        public string ID { get; set; }
     }

but in java,i don't know how to do, i didn't found @BsonRepresentation or like something 但是在java中,我不知道该怎么做,我没有找到@BsonRepresentation或类似的东西

when i write like this, it error 当我这样写的时候

public class User_ObjectID implements EntityStringKey {
    //
    @BsonId
    private String id;

    //#region 
    public String getId(){return id;}

    public void setId(String id){this.id = id;}
    //#endregion
}

Error Message: An exception occurred when decoding using the AutomaticPojoCodec. 错误消息:使用AutomaticPojoCodec解码时发生异常。 Decoding into a 'User_ObjectID' failed with the following exception: 解码为“ User_ObjectID”失败,但存在以下异常:

Failed to decode '_id'. readString can only be called when CurrentBSONType is STRING, not when CurrentBSONType is OBJECT_ID.

A custom Codec or PojoCodec may need to be explicitly configured and registered to handle this type.

Instead of using String for id, You need to use ObjectId class. 无需使用String作为id,您需要使用ObjectId类。 This class maps _id of mongoDB to Java 此类将mongoDB的_id映射到Java

private ObjectId id;

After Getting the object, you can get the _id String by - 获取对象后,可以通过以下方式获取_id字符串:

id.toString(); 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM