简体   繁体   中英

Wildcard escaping JPA Specifications

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.

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 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();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM