Search code examples
javamongodbmorphia

Morphia @Version Not Working


I am using morphia 0.109 and have defined a base class as follows:

@Entity
public abstract class MorphiaData {
    @Id protected ObjectId objectId;
    @Version private Long mongodocversion;
}

And the intended Morphia entity

public class ItemTest extends MorphiaData {
    public Long testValue;
}

When I save an instance of ItemTest to mongoDB the document looks as follows:

{
    "_id" : ObjectId("54d26ed66aca89c0717e8936"),
    "className" : "test.ItemTest",
    "testValue" : NumberLong(1423077078)
}

I am expecting to see a value of mongodocversion in the document.

The morphia documentation provides the following information regarding the version annotation:

This field will be automatically managed for you -- there is no need to set a value and you should not do so anyway.

@Entity
class MyClass {
   ...
   @Version Long v;
}

which I believe I am adhering too. I have attempted the following fixes without success:

  1. Moving the version annotation in the child class.
  2. Removing the 'private' declaration of the version parameter.

Any advice would be greatly appreciated.

Edit to add: The save process I am using:

DBObject document = MongoDbFactory.getMorphia().toDBObject(this);

DB db = MongoDbFactory.getClient();
DBCollection coll = db.getCollection(noSqlCollection.toString());

if (this.objectId != null) {
    //This is an update
    BasicDBObject searchQuery = new BasicDBObject().append("_id", this.objectId);
    coll.update(searchQuery, document);
} else {
    //This is just an add
    coll.insert(document);
    this.objectId = (ObjectId)document.get( "_id" );
}

Solution

  • This test currently is passing on jenkins: https://github.com/mongodb/morphia/blob/master/morphia/src/test/java/org/mongodb/morphia/optimisticlocks/VersionTest.java#L20-20