I use JacksonDBCollection (mongojack 2.0.0-RC1) to write Java objects to my MongoDB. Classes to be mapped inherit from this implementation:
import org.mongojack.ObjectId;
import com.fasterxml.jackson.annotation.JsonProperty;
public class IdentifiableObject implements Serializable {
private String id;
@ObjectId
@JsonProperty("_id")
public String getId() {
return id;
}
@ObjectId
@JsonProperty("_id")
public void setId(String id) {
}
}
Basically, this seems to work. An object written to Mongo looks like this:
{ "_id" : ObjectId("512203b24cca3cbcac0fbad6"), ... }
JacksonDBCollection.insert's WriteResult.getSavedId() returns the expected 512203b24cca3cbcac0fbad6. But reading these object from Mongo does not convert the ObjectId as expected:
IdentifiableObject myObj = myJacksonDBCollection.findOneById("512203b24cca3cbcac0fbad6");
System.out.print(myObj.getId()); // prints "de.undercouch.bson4jackson.types.ObjectId@6f45d7f2"
As you can see the ObjectId is converted using Java's native toString or something similar. I want the ID to be 512203b24cca3cbcac0fbad6 again. I hope somebody can tell me why this happens and how I can fix this.