Search code examples
mongodbdaomorphia

Morphia Single dao for multiple collection MongoDB


Can the morphia single BasicDAO handle/query multiple collection, may by be by overloading function with the class parameter.

public class GenericDAO extends BasicDAO<T, K> {

  /* override count impl*/
  public long count(Class<T> clazz) {
     return ds.getCount(clazz);
  }
}

Is there any other way I can query two different collection using single DOA or it is better to make separate DAO for each collection.

Example For User and BlogEntry Collections

public class BlogEntryDAO extends BasicDAO<BlogEntry, ObjectId>
public class UserDAO extends BasicDAO<User, ObjectId>

Solution

  • The simple answer is NO,

    The BasicDAO is made made on the assumption to deal with single collection/Entity as many of the DOA's function are Entity/Class and _id/primary key type based.

    public class BasicDOA<T,K> implements DOA<T,K>
    

    T should be a specific class
    K should be a specific key (can be separate for different class) e.g ObjectId, String, Long etc

    Example function

    public Class<T> getEntityClass()
    public T get(K id)
    

    If you want to deal with multiple collection in single DAO then create your own generic DAO with custom methods and use DataStore to deal with different/specific collections.

    public class MyDAO {
      protected DatastoreImpl ds;
    
      public count(Class<T> clazz) {
        return ds.getCount(clazz);
      }
    
      public T get(Class<T> clazz, K id) {
         return ds.get(clazz, id);
      }
    }