简体   繁体   English

NativeQuery是更好的还是HibernateOGM方法

[英]NativeQuery is better or HibernateOGM methods

I am using hibernate OGM to talk to my MongoDB instance. 我正在使用休眠OGM与我的MongoDB实例进行对话。 I had to get a list of all the products with category "abc" . 我必须获取所有类别为"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? 我可以使用.find()方法实现同一目的吗? We are using vertx server with gradle as building tool. 我们正在使用带有gradle的vertx服务器作为构建工具。

Do you mean the EntityManager.find() ? 您是说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: 您可以做的是编写JP-QL查询:

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 . 我假设您有一个实体Product ,其属性为category

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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