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?
The id generation rules are explained here link
One alternative could be to let
DocumentDB/ MongoDB
create thoseIDs
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.