1

I am using hibernate OGM to talk to my MongoDB instance. I had to get a list of all the products with category "abc". I am using the native query approach to achieve this as following:

String stringQuery = "db.Message.find({'CATEGORY':'" + category + "})";
Query query = entityManagerProvider.get().createNativeQuery(stringQuery, Product.class);
productList = query.getResultList();

I am not sure if it is the right approach to do this as I see a too much hard coding (look at the collection name). Can I use the .find() method to achieve the same thing? We are using vertx server with gradle as building tool.

Obaid Maroof
  • 1,523
  • 2
  • 19
  • 40

1 Answers1

1

Do you mean the EntityManager.find()? You can use it if you filter using the primary key. It doesn't seem the case in your example.

What you can do is write a JP-QL query:

productList = entityManagerProvider.get().createQuery( "SELECT p FROM Product p WHERE p.category=:category", Product.class ).setParameter("category", category).getResultList();

I'm assuming that you have an entity Product with attribute category.

Davide D'Alto
  • 7,421
  • 2
  • 16
  • 30
  • Would that work with mongoDB as well? And is this a better approach then using the nativeQuery? – Obaid Maroof Jan 14 '16 at 12:24
  • 1
    Yes, it will work with MongoDB. I think it is a better approach because it is portable. The same query will work on other datastores as well the moment you are going to change backend. Hibernate OGM will also be able to adapt the query in case you change some things about the mapping. – Davide D'Alto Dec 13 '16 at 16:31