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

时间:2017-12-01 07:48:13

标签: java c# mongodb

在mongodb:

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

在C#中,我可以使用它(ps:我需要设置字符串ID,而不是ObjectID)

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

但在java中,我不知道该怎么办 我没有找到@BsonRepresentation或喜欢的东西

当我这样写时,它出错了

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
}

错误讯息: 使用AutomaticPojoCodec解码时发生异常。 解码为“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.

1 个答案:

答案 0 :(得分:0)

您需要使用ObjectId类,而不是使用String作为id。该类将mongoDB的_id映射到Java

private ObjectId id;

获取对象后,您可以通过 -

获取_id字符串
id.toString(); 
相关问题