How to use a native db operator (postgres ~ ) with JPA criteria builder?

谁说我不能喝 提交于 2019-12-08 08:09:50

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!