Search code examples
javahibernatenativequeryhibernate-ogmhibernate-native-query

NativeQuery is better or HibernateOGM methods


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.


Solution

  • 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.