本文介绍了Criteriabuilder之类的,对于Long来说该怎么做?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我尝试使用Criteriabuilder中的"like"方法来获取所有基于模式"10%"的记录.

i try use "like" method from Criteriabuilder for get all record based on pattern " 10% ".

我想获取ID为-101、10002、1003、1000等的记录...

I want get record where ID is - 101, 10002, 1003,1000 etc...

我已经使用以下代码:

Predicate p = cb.like(r.<String>get("ID").as(String.class), "10%")

但是我遇到了异常,在那里我看到哪些postgres无法执行这样的查询:

but i got Exception where i see what postgres can't execute query like this:

SELECT ID, NAME, SOMETHING FROM TABLE WHERE ID LIKE 10%

即JPA(Glassfish 4.x)生成错误查询.

正确的查询必须这样:

SELECT ID, NAME, SOMETHING FROM TABLE WHERE CAST (ID as TEXT) LIKE '10%'

如何通过Criteria API建立查询,以获取对postgres的正确查询?

How to build query via Criteria API that i got a right query for postgres ?

已更新:

我尝试编写一个CAST函数:

I try write a CAST function :

Expression<String> postgresqlCastFunction = cb.function("CAST", String.class, r.<String>get("ID").as(String.class));
Predicate p = cb.like(postgresqlCastFunction, "10%");

但是得到了这样的查询:

but got a query like this :

FROM TABLE WHERE (CAST(ID) LIKE ?)

,因此,如何在函数中为这个正确的结果添加需求表达式-

, so, how to add need expression in function for this right result -

从表的位置(例如,是否为CAST(ID 为文本的文本)?)..

FROM TABLE WHERE (CAST(ID as TEXT) LIKE ?) ..

推荐答案

使用PostgreSQL本机 TO_CHAR 函数可能如下所示:

An example implementation using PostgreSQL native TO_CHAR function may look as follows:

JPQL

SELECT r FROM Records r 
WHERE FUNCTION('TO_CHAR', r.ID, 'FM9999999999') LIKE :pattern

标准API

Path<String> id = r.get("ID");
Expression<String> format = cb.literal("FM9999999999");
Expression<String> function= cb.function("TO_CHAR", String.class, id, format);
ParameterExpression<String> pattern = cb.parameter(String.class, "pattern");
Predicate like = cb.like(function, pattern);
cq.where(like);

您还可以将查询作为单行构建:

also you can build the query as an one-liner:

cq.where(cb.like(cb.function("TO_CHAR", String.class, r.get("ID"), cb.literal("FM9999999999")), cb.parameter(String.class, "pattern")));


执行上述查询:


Execute the above query:

Query q = em.createQuery(cq).setParameter("pattern", "10%");

这篇关于Criteriabuilder之类的,对于Long来说该怎么做?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-29 11:10