【问题标题】:how to create Sum Function in Spring JPA + Query DSL using PathBuilder如何使用 PathBuilder 在 Spring JPA + Query DSL 中创建 Sum 函数
【发布时间】:2016-08-15 07:31:03
【问题描述】:

我有如下查询

select sum(qty)... from table where productname = 'Pepsi' group by product.

我在PathBuilderQueryDSL下面创建了Spring代码:-

PathBuilder<Stock> entityPath = new PathBuilder<Stock>(Stock.class, "stock");
BooleanPath path = entityPath.getBoolean("productname");
BooleanExpression wherecondition = path.eq("pepsi");

NumberPath<Double> path = entityPath.getNumber("qty", Double.class);
NumberExpression<Double> sumfunction= path.castToNum(Double.class).sum();

我正在使用 JPA 存储库来获取如下可分页数据:-

Page<Stock> page = stockRepository.findAll(wherecondition,pageable);

我不知道如何将上面的sumfunction 与 JPA 存储库一起使用。因为我不能结合BooleanExpressionNumberExpression

【问题讨论】:

  • 使用查询 dsl 的任何具体原因?
  • 因为查询是动态的,基于来自前端的过滤器
  • 这是唯一的条件 productname = 'Pepsi' 还是您拥有的任何其他条件?我假设 productname 的值是动态的,即 Pepsi 可能会根据用户选择而变化。

标签: java spring spring-data-jpa querydsl


【解决方案1】:

你试过这样吗

@Configurable
public interface XXRepository extends PagingAndSortingRepository<xx, String> {

@Query(value = "select sum(qty)... from table where productname = ?1 group by product", nativeQuery = true)
      public String findSumOfQty(String productname);
}

xx = 代表表格的实体名称。

【讨论】:

  • 我们可以有许多 where 条件,这就是我不能使用 @Query 注释的原因。
猜你喜欢
  • 2017-08-21
  • 1970-01-01
  • 1970-01-01
  • 2015-06-09
  • 1970-01-01
  • 1970-01-01
  • 2017-02-15
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多