简体   繁体   中英

Is it good practice to pass collection name in Morphia createQuery method?

I usually use this approach while instantiating the query object:

Query<Product> query = datastore.createQuery(Product.class);

But Morphia allows you to pass the collection name also while instantiating the query object, which would look like this:

Query<Product> query = datastore.createQuery(COLLECTION_NAME, Product.class);

I am unable to understand why do we have to pass the Collection name explicitly while creating the query object?

When we create the model, in this case in the Product class we are already binding the collection name under the Entity annotation:

@Entity(value = "product", noClassnameStored = true)
class Product {
  // model attributes declared here
}

One reason I can think of is, if the same model is used across multiple collection then we might need to pass the collection name, but even if it is so is this a good practise and does it abide the ORM guidelines? Please help me understand.

That method is used for cases where one entity is stored in different collections depending on the application usage. It's "hidden" on the AdvancedDatastore interface so that all you should see on a Datastore reference is the one createQuery() that takes the type. Most users won't need the overridden form but it was added years ago as a convenience for those who needed to map to multiple locations.

It's a mild misfeature as it doesn't quite work well with @Reference fields. I'm not sure how long that feature will continue to exist as it complicates some of the implementation for very little benefit.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM