Search code examples
javamongodbpojomorphianosql

MongoDB Morphia save() generates two objects with the same ID


I have a java application that connects to a MongoDB Database through the Morphia library. My POJO that I store in the database has String field named _id and annotated with the @Id annotation (com.google.code.morphia.annotations.Id;).

I'm generating a new object ( it has null _id). I call save(object) on the datastore provided by morphia. The object gets updated after being stored and now has an _id value. I call save(object) again and a new entry is created in the database with the same _id. All consecutive save() operations on the object overwrite the old one and do not produce any new entries in the database.

So for example, after 10 save() calls on the same object my database ends up looking like this:

{ "_id" : { "$oid" : "539ade7ee4b0451f28ba0e2e"} , "className" : "blabla" , blabla ...}
{ "_id" : "539ade7ee4b0451f28ba0e2e" , "className" : "blabla" , blabla ...}

As seen those two entries have the same _id but with different representation. One has it as an object the other as a string. Normally I should have only one entry shouldn't I ?


Solution

  • Do not use a string for the _id. This will fix your problem:

    @Id
    protected ObjectId id;
    

    While you could use protected String id (this shouldn't create duplicates IMHO), you'll have problems if you use @Reference and might run into weird edge cases elsewhere, so avoid it if possible.