通配符转义 JPA 规范 [英] Wildcard escaping JPA Specifications

查看:26
本文介绍了通配符转义 JPA 规范的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 JPA Specifications Executor 根据用户在 UI 上的输入通过记录实现搜索.例如,应该使用 LIKE 子句在 message 列中搜索输入之一.目前我已经这样做了:

I am using JPA Specifications Executor to implement search via records based on the user's input on UI. For instance, one of the inputs should be searched in column message using LIKE clause. Currently I have done it like this:

if (StringUtils.isNotBlank(searchOptions.getSearchString())) {
     String likeExpression = String.format("%%%s%%", searchOptions.getSearchString());
     specifications = specifications.and(
         (root, query, cb) -> cb.like(root.get("message"), likeExpression));
}

问题是,如果用户的输入包含像 % 这样的通配符或 [] 中的一些文本,我不会将其作为文字进行搜索,而是将其视为通配符.

The problem is, if the user's input contains wildcards like % or some text inside [], I does not search for it as a literal, but treat is as a wildcard.

谁能建议我如何避免这种情况并始终搜索列中的文字文本,而不必手动转义 Java 代码中的每个此类字符?

Can anyone suggest me how to avoid this and always search for the literal text in the column without having to manually escape every such character in java code?

我使用的 RDBS 是 SQL Server.

RDBS I am using is SQL Server.

推荐答案

您应该绑定一个参数,而不是将其插入到您的表达式字符串中.

You should be binding a parameter instead of inserting it into your expression string.

CriteriaQuery<Person> criteria = build.createQuery( Person.class );
Root<Person> personRoot = criteria.from( Person.class );
 criteria.select( personRoot );
 ParameterExpression<String> eyeColorParam = builder.parameter( String.class );
 criteria.where( builder.equal( personRoot.get( Person_.eyeColor ), eyeColorParam ) );
 TypedQuery<Person> query = em.createQuery( criteria );
query.setParameter( eyeColorParam, "brown" );
List<Person> people = query.getResultList();

这篇关于通配符转义 JPA 规范的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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