I'm trying to retrieve a Java object from MongoDB using the Morphia library as described here. This requires that the entity class be specified; however, I'm going to be iterating over a list of collections, and want to be able to arbitrarily translate DBObjects into their respective Java objects.
Morphia stores the Java association in the className
field, so is there a way to leverage this so that I don't have explicitly define the entity class?
Generics are your friend. Your entities should inherit from a base entity. Then you can generic queries such as this:
public <E extends BaseEntity> ObjectId persist(E entity) {
mongoDatastore.save(entity);
return entity.getId();
}
For a full code example take a look at this: https://github.com/xeraa/morphia-demo/blob/master/src/main/java/net/xeraa/morphia_demo/entities/BaseEntity.java