问题
I am using JPA 2.0 criteria to build the following query (simplified):
select n from notif n where n.message ~ 'b.*la'
I am using postgresql db, and I really need the ~ operator,not like. Is there something equivalent to the CriteriaBuilder.function I can use? Alternatively, is there a function form of the ~ operator in postgres so I can use the mentioned cb.function method. I have only found the postgresql regexp_matches function, but it returns an array of matches not a boolean.
Solution: Since moving from the criteria API to JPQL was out of the question, I ended up writing a postgres function:
'CREATE OR REPLACE FUNCTION "regexp_search"(character varying,character varying) RETURNS boolean AS \'select $1 ~ $2;\' LANGUAGE sql;'
And calling it with cb.function:
Expression<Boolean> regexp_search = cb.function("regexp_search", Boolean.class, message,cb.literal(re));
回答1:
REGEXP or ~ are not part of the JPQL standard. You could use a native SQL query.
If using EclipseLink, REGEXP is supported, and will work on Postgres,
http://www.eclipse.org/eclipselink/documentation/2.4/jpa/extensions/j_regexp.htm#regexp
You can also use the SQL function to call any SQL specific syntax inside JPQL,
http://www.eclipse.org/eclipselink/documentation/2.4/jpa/extensions/j_sql.htm#sql
来源:https://stackoverflow.com/questions/14137479/how-to-use-a-native-db-operator-postgres-with-jpa-criteria-builder