Escape character in JPQL
In JPQL what is an escape character we can use to remove characters like "'"
Example: I am doing something like
"... where person.name = 'Andy'"
Here it works fine
but when the person's name is Andy, then the where clause becomes like
"... where person.name = 'Andy's'"
and it returns an error saying
It cannot figure out where the string literal ends. The solution is well stated in the spec:
A string literal that includes one quote is represented by two single quotes - for example: "literals".
In your case, this means:
...where person.name='Andy''s'
Below is a sample code to execute a query using a named parameter.
Query query = entityManager.createQuery("SELECT p FROM Person p WHERE p.name LIKE :name" );
query.setParameter("name", personName);
Here you can pass a string to personName
which can contain a special character such as "Andy's".
Also, it looks very clean and doesn't require parameter validation before executing the query and changing the search string.