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

147 views Asked by At

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);
}
2

There are 2 answers

0
Lebowski On BEST ANSWER

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.

0
BkSouX On

Thanks. Here is the answer:

 if (entity.getId() == null) {
    DBCollection ids = getDatastore().getDB().getCollection("ids");
    BasicDBObject findQuery = new BasicDBObject("_id", getClass().getSimpleName());
    DBObject incQuery = new BasicDBObject("$inc", new BasicDBObject("value", 1));
    DBObject result = ids.findAndModify(findQuery, incQuery);
    entity.setId(result == null || !result.containsField("value") ? 1L : (Long) result.get("value"));
 }