3

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?

BalusC
  • 1,082,665
  • 372
  • 3,610
  • 3,555
user2061913
  • 910
  • 2
  • 14
  • 34
  • That error message seems to be pretty clear. Im confused as to what assistance you're seeking. If you have a code question you'll need to post some code. – Peter Foti Nov 19 '13 at 19:59
  • Read the error. You've probably got a placeholder `:foo` in your query, but are trying to bind a value for `:baz` or something like that. – Marc B Nov 19 '13 at 20:03
  • sorry this is my first project like this and using these technologies, what is causing this error, the fields in the database are only i.d. and username, the username is what i trying to return, i just dont understand how i can fix this – user2061913 Nov 19 '13 at 20:04
  • 2
    The problem is in your JPA code from your last question: http://stackoverflow.com/q/20080195/1065197. You have `:username` as named parameter but setting `string` in `return getEntityManager().createNamedQuery("Userdetails.findByUsername").setParameter("string", "%" + string + "%").getResultList();`. – Luiggi Mendoza Nov 19 '13 at 20:05
  • Thanks a lot i think it is working now, i jsut have to display the results but think i need some sleep now ! thanks guys – user2061913 Nov 19 '13 at 20:08

1 Answers1

7

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();
Luiggi Mendoza
  • 85,076
  • 16
  • 154
  • 332