Search code examples
javamongodbmorphia

Morphia - How to replace LongIdEntity.StoredId in last version?


I just switched to the last version of Morphia (1.0.1). The previous one was com.github.jmkgreen.morphia 1.2.3.

I don't know how to replace LongIdEntity.StoredId. I use it to increment a long id.

edit : Here is how it worked before:

public Key<Snapshot> save(PTSnapshot entity) {
    if (entity.getId() == null) {
        String collName = ds.getCollection(getClass()).getName();
        Query<StoredId> q = ds.find(StoredId.class, "_id", collName);
        UpdateOperations<StoredId> uOps = ds.createUpdateOperations(StoredId.class).inc("value");
        StoredId newId = ds.findAndModify(q, uOps);
        if (newId == null) {
            newId = new StoredId(collName);
            ds.save(newId);
        }
        entity.setId(newId.getValue());
    }
    return super.save(entity);
}

Solution

  • StoredId class is just a POJO with 3 fields:

    • id
    • className (to store the type of object the auto-increment will be done on, but you could store something lese, this is just used to retrieve the adequate increment value, because you could have more than one auto-incremented collection !)
    • value (to store the current value of the auto-increment)

    But it is just an helper, you can reproduce the behavior all by yourself. Basically you just need a collection where you store a simple number, and increment it with findAndModify() each time a new object is inserted.

    My thought is that Morphia/Mongo decided to remove this because auto-increments are not recommended with Mongo databases, and ObjectIds are more powerful.