在JPA CriteriaBuilder中使用正则表达式 [英] Use Regular Expressions in JPA CriteriaBuilder
问题描述
我使用JPA CriteriaBuilder从MySQL数据库中选择类型为 MyEntity
的实体,如下所示:
字符串regExp =(abc | def)
CriteriaBuilder cb = em.getCriteriaBuilder();
CriteriaQuery query = cb.createQuery(MyEntity.class);
root = query.from(MyEntity.class);
predicates = new ArrayList< Predicate>();
predicates.add(cb.like(root。< String> get(name),regExp));
因此,查询结果应该包含名称
值与给定的regExp匹配。但结果列表总是空的。
将regExp更改为 /(abc | def)/ g
不起作用,添加通配符%$ c $如何使模式匹配工作?
另外:我怎样才能使用本机MySQL REGEXP在一起使用CriteriaBuilder?
JPA查询中的模式匹配仅限于
_
- 任何字元
%
- 任何字符串
REGEXP
c $ c> SELECT'a'REGEXP'A'),所以它不能与 CriteriaBuilder.function()
API一起使用。恐怕最好是运行原生SQL查询。
如果您使用Hibernate,您还有一个选项。您可以在 SQLFunctionTemplate $ c中包装
并使用 REGEXP
运算符$ c>,扩展hibernate方言 CriteriaBuilder.function()
运行。
I'm using the JPA CriteriaBuilder to select entities of type MyEntity
from a MySQL db as follows:
String regExp = "(abc|def)"
CriteriaBuilder cb = em.getCriteriaBuilder();
CriteriaQuery query = cb.createQuery( MyEntity.class );
root = query.from( MyEntity.class );
predicates = new ArrayList<Predicate>();
predicates.add( cb.like( root.<String>get( "name" ), regExp ) );
Thus, the query result should contain any entity where the name
value matches the given regExp. But the result list is always empty.
Changing the regExp to /(abc|def)/g
has no effect, neither does adding the wildcard %
How to make the pattern matching work?
Alternatively: How can I use native MySQL REGEXP together with the CriteriaBuilder?
Pattern matching in JPA queries is limited only to
_
- any character%
- any string
REGEXP
has operator syntax in MySQL (SELECT 'a' REGEXP 'A'
) so it cannot be used with CriteriaBuilder.function()
API. I'm afraid the best is to run native SQL query.
If you are using Hibernate you have one more option. You can wrap REGEXP
operator in SQLFunctionTemplate
, extend hibernate dialect and run with CriteriaBuilder.function()
.
这篇关于在JPA CriteriaBuilder中使用正则表达式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!