【问题标题】:Java Criteria query for amount range regardless of amount signJava Criteria 查询金额范围,无论金额符号如何
【发布时间】:2017-10-19 07:51:18
【问题描述】:

我想根据金额范围对数据库数据进行搜索,有一些金额项也是负数。但无论有什么迹象,我都想使用 javax.persistence.criteria 将我的标准应用于实际金额。

例如查询输入:1到100之间

预期输出:-99 ,-10 , 33 ,90 100

有人可以指导我吗?

【问题讨论】:

  • 你的意思是使用ABS(field)?请解释为什么这很困难以及您尝试了什么
  • 嗨,我想要以下查询的 jpa 条件谓词:select * from Table where abs(cast(amount as decimal(10,2))) 介于 1 和 800 之间。
  • 那么你有什么尝试?其中哪个特定部分很难? CriteriaBuilder 上有所有这些方法(abs、cast、between)。哦,把它放在你的问题中,而不是在 cmets 中
  • 嘿,设法使用谓词处理强制转换,但我不知道如何在这个谓词上应用 abs .. 谓词 matchPrice = cb.between(trxRoot.get("amount").as (BigDecimal.class), minPrice, toAmount);
  • @BillyFrost 感谢您的建议和帮助。我想通了...

标签: java mysql jpa persistence criteria-api


【解决方案1】:

Sql 查询:

select * from table where abs(cast(amount as decimal(10,2))) between 1 and 700

条件查询:

final List<Predicate> predicates = new ArrayList<>();
Predicate matchPrice = cb.between(cb.abs(trxRoot.get("amount").as(BigDecimal.class)), minPrice, toAmount);
predicates.add(matchPrice);
query.where(predicates.toArray(new Predicate[] {}));

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2022-06-13
    • 2020-07-31
    • 1970-01-01
    • 1970-01-01
    • 2019-10-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多