JPA 标准构建器:如何按顺序替换字符串并将其转换为数字?

有人可以建议我如何使用 JPA Criteria builder API 构建以下查询吗?


SELECT id, name, date, version FROM public.upgradeTable

order by (CAST(replace(version, '.', '')AS numeric)) desc;

请注意我们的版本列有像“11.0.2.213”、“11.0.2.73”这样的值我们需要修剪字符“.” 在版本中,然后将它们转换为数字,然后按 desc 排序。


HUH函数
浏览 154回答 1
1回答

慕勒3428872

目前 JPA 没有用于 replace() 和 cast(string as numeric) 的 API。但是,如果数据库可移植性不重要,您可以使用 CriteriaBuilder.function(...) 来创建数据库本机函数。对于 MySQL,您的示例的 order-by 表达式将是:&nbsp; &nbsp; Expression<String> replacedValue = criteriaBuilder.function("replace",&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; String.class, root.get("version"), criteriaBuilder.literal("."),&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; criteriaBuilder.literal(""));&nbsp; &nbsp; Expression<String> lpadValue = criteriaBuilder.function("lpad",&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; String.class, replacedValue, criteriaBuilder.literal(20),&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; criteriaBuilder.literal("0"));&nbsp; &nbsp; criteriaQuery.orderBy(criteriaBuilder.desc(lpadValue));CriteriaBuilder.function(...) 不支持诸如cast(value as type) or convert(value, type). 所以使用 lpad(...) 来实现相同的 orderBy 结果。它适用于Cmobilecom JPA,这是一个适用于 Java 和 Android 的轻量级 JPA实现。
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java