How to use 'id' when using DocumentDB via MongDB API in Spring DATA?

倖福魔咒の 提交于 2019-12-12 02:07:38

问题


I have used both the ways of mapping _id as described in the Spring Docs here.

  • using @Id annotation
  • having a field with name id without any annotation

in my previous project where we used MongoDB as database and Spring Data for DAO operations. It worked without any problem for both String a well as for BigInteger.

Now we are using DocumentDB with MongoDB API(as Spring Data does not support DocumentDB). I am able to use all the Spring Data methods, but I am not able to use custom id.

Below is my entity:

public class S{

    private String id;

    /* other fields here */

    public String getId() {
        return id;
    }

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

    /* getters and setters for other fields */
}

This is the DAO:

public interface SDao extends MongoRepository<S, String> {

}

Now if anywhere in my code I do:

s = new S();
s.setId("some-id-here");

The record gets successfully persisted in the DB with custom id some-id-here as String (not ObjectId), but after that it throws ClassCastException saying Long cannot be converted to Integer.

Same is the case when using BigInteger for id.

If I am not setting the custom id, i.e. I comment the setting of id as below:

s = new S();
// s.setId("some-id-here");

no exception is being thrown, but the record is being persisted with a random id provided by database itself as ObjectcId.

I want to save the record with custom id, so that I can easily update it when needed. Currently if I have to update a record, I need to retrieve it using a key which is not mapped to _id and then update it and then delete the old record from the DB and then persist the updated one, which I feel is absolutely inefficient as I am not able to make use of _id.

My question is why am I getting ClassCastException, that too mentioning Conversion of Long to Integer

Is DocumentDB internally doing some conversion which is throwing this exception. If yes, how to tackle it? Is this a bug?


回答1:


One alternative could be to let DocumentDB/ MongoDB create those IDs for you by default. In your class you can have another field which can serve as natural ID and create a unique index on that field for fetch optimization. Refer https://docs.mongodb.com/manual/reference/method/db.collection.createIndex/ for indexes.




回答2:


The id generation rules are explained here link



来源:https://stackoverflow.com/questions/42383336/how-to-use-id-when-using-documentdb-via-mongdb-api-in-spring-data

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!