【问题标题】:QueryDSL Predicate (Data JPA) which will query all the records by some rule and group them?QueryDSL Predicate (Data JPA) 将通过某些规则查询所有记录并将它们分组?
【发布时间】:2015-06-10 21:22:47
【问题描述】:

如果我的数据库中有产品表,并且我想查询 20 个最昂贵的产品。

SELECT p FROM Products p ORDER BY p.price DESC LIMIT 20

我怎样才能把它翻译成 QueryDSL 谓词,甚至有可能吗?我已经阅读了很多教程和其他内容,并且看到过这样的事情:

QProducts p = QProducts.product;
JPAQuery query = new JPAQuery(entityManager);
     query.from(p).orderBy(p.price.price.asc().limit(20));

我没有在我的程序中使用过 JPA EntityManager,所以我不知道该怎么做。到目前为止,我只完成了这样的查询,并且它们在没有任何 EntityManager 的情况下工作得很好。

public static Predicate productName(String searchTerm){
     QProduct product = QProduct.product;
     return product.name.startsWithIgnoreCase(searchTerm);
}

我只是将该谓词传递给 Spring DATA JPA 提供的方法。我怎样才能用我以前的谓词这样的风格来解决我上面描述的问题?

【问题讨论】:

    标签: jpa spring-data-jpa querydsl


    【解决方案1】:

    不,orderBy 和 limit 子句不能成为 Predicate 的一部分。

    但是当您使用 Spring Data JPA 时,您的 Spring 上下文中应该有一个 EntityManager。 尝试像这样将它连接到您的自定义存储库中:

    @PersistenceContext
    protected EntityManager em;
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-03-29
      • 2015-05-11
      • 2020-10-06
      • 2016-02-17
      • 1970-01-01
      • 2020-01-18
      • 2015-02-08
      • 2020-06-05
      相关资源
      最近更新 更多