andPat
andPat

Reputation: 4522

Insert special characters in JPA query with set parameter

Is there a way in JPA 2.0 to set parameter of a query with special characters? I mean, if I do: query.setParameter(field, "%" + value.toString() + "%");, it takes % as special (wildcard) character? It seems to me it's not true in this case, beacuse my search doesn't work with truncated words... Can You help me??

Upvotes: 1

Views: 7520

Answers (3)

Sai prateek
Sai prateek

Reputation: 11906

If you are using

LIKE :feild 

for

query.setParameter(field, "%" + value.toString() + "%");

Then value remains free from the '%' sign. You can try to use % in your query and send value from setParameter() method.

You can also try CreteriaBuilderInterface of JPA. http://www.objectdb.com/java/jpa/query/jpql/string.

Upvotes: 1

user2880879
user2880879

Reputation: 297

what ever you pass in as a query parameter that will pass on to query and back to database. So to the choice of escape character of the query parameter will depend on database. Like in mysql it is "\'" for "'" and "\%" for "%" so if I want to send "john's 10% commission" as query parameter to mysql, i will try query.setParameter(field, "john\\'s 10\\% commission"); in your case query.setParameter(field, "\\%" + value.toString() + "\\%"); should work. But check the documentation of the database to find out escape character for special cases.

Upvotes: 0

Roman K
Roman K

Reputation: 3337

you have to escape the query. try to use "\\%" instead

Upvotes: 0

Related Questions