我使用 JPA (Hibernate) 作为持久层。
我需要添加一个基于正则表达式的 WHERE 子句, 这样的一些模式是 SELECT * FROM TableName where REGEXP_LIKE(ColumnName, 'Pattern')。我从结果中得到的是字符串列表,但我需要从数据库中获取映射实体作为对象而不是字符串。
据我所知,JPQL 可以将结果作为对象返回,但 JPQL 似乎不支持正则表达式,因为它是 Oracle 的专有扩展。
如何将正则表达式应用于 JPQL?我还需要了解什么?
最佳答案
JPQL 中没有完整的正则表达式,但有模式值。根据规范JPQL 2.2 (p. 188) :
The pattern_value is a string literal or a string-valued input parameter in which an underscore (_) stands for any single character, a percent (%) character stands for any sequence of characters (including the empty sequence), and all other characters stand for themselves.
[...]
Examples:
address.phone LIKE ‘12%3’ is true for ‘123’ ‘12993’ and false for ‘1234’
asentence.word LIKE ‘l_se’ is true for ‘lose’ and false for ‘loose’
aword.underscored LIKE ‘_%’ ESCAPE ‘\’ is true for ‘_foo’ and false for ‘bar’
address.phone NOT LIKE ‘12%3’ is false for ‘123’ and ‘12993’ and true for ‘1234’
如果您想要更高级的正则表达式构造,您需要使用 native 查询。
关于regex - 如何在JPQL中应用正则表达式?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9733667/