在JPA CriteriaBuilder中使用正则表达式 [英] Use Regular Expressions in JPA CriteriaBuilder

查看:2202
本文介绍了在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 不起作用,添加通配符

另外:我怎样才能使用本机MySQL REGEXP在一起使用CriteriaBuilder?

解决方案

JPA查询中的模式匹配仅限于


  • _ - 任何字元

  • - 任何字符串



REGEXP c $ c> SELECT'a'REGEXP'A'),所以它不能与 CriteriaBuilder.function() API一起使用。恐怕最好是运行原生SQL查询。



如果您使用Hibernate,您还有一个选项。您可以 SQLFunctionTemplate 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆