java.lang.IllegalArgumentException: You have attempted to set a parameter value using a name of string that does not exist in the query string

user2061913 picture user2061913 · Nov 19, 2013 · Viewed 13k times · Source

I have the following named query:

@NamedQuery(
    name = "Userdetails.findByUsername", 
    query = "SELECT u FROM Userdetails u WHERE u.username = :username"
)

When I try to execute it as follows:

getEntityManager()
    .createNamedQuery("Userdetails.findByUsername")
    .setParameter("string", "%" + string + "%")
    .getResultList();

Then I get the following exception:

java.lang.IllegalArgumentException: You have attempted to set a parameter value using a name of string that does not exist in the query string SELECT u FROM Userdetails u WHERE u.username = :username.

How is this caused and how can I solve it?

Answer

Luiggi Mendoza picture Luiggi Mendoza · Nov 19, 2013

Here in your Userdetails.findByUsername named query you have a named parameter called username:

SELECT u FROM Userdetails u WHERE u.username = :username

Then you call it using the Entity Manager but set a string parameter:

getEntityManager()
    .createNamedQuery("Userdetails.findByUsername")
    .setParameter("string", "%" + string + "%") //<-- check here
    .getResultList();

Replace this string parameter by username:

getEntityManager()
    .createNamedQuery("Userdetails.findByUsername")
    .setParameter("username", "%" + string + "%") //<-- check here
    .getResultList();