Search code examples
javahibernatehqlentitymanagernamed-parameters

IllegalArgumentException: Could not locate named parameter


I pass a Map as parameter of the following method:

    public List<User> getByParameterOrAll(Map<String, String> paramsMap) {
    String email = null;
    String emailValue = null;
    String phone = null;
    String phoneValue = null;

    Iterator<Map.Entry<String, String>> entries = paramsMap.entrySet().iterator();
    while (entries.hasNext()) {
        Map.Entry<String, String> entry = entries.next();
        if (entry.getKey().equals("email")){
            email = entry.getKey();
            emailValue = entry.getValue();
        } else if (entry.getKey().equals("phone")){
            phone = entry.getKey();
            phoneValue = entry.getValue();
        }
    }

    List<User> users = em.createQuery("SELECT u FROM User u WHERE u.email=:emailValue AND u.phone=:phoneValue", User.class).
            setParameter(emailValue, email).
            setParameter(phoneValue, phone).
            getResultList();
    return users;
}

And I catch for the line "setParameter(emailValue, email)"

java.lang.IllegalArgumentException: Could not locate named parameter [[email protected]], expecting one of [phoneValue, emailValue]

I attach the screen of my test

Testing_screen


Solution

  • You should correct your query in the following way (see the documentation) :

    List<User> users = em.createQuery("SELECT u FROM User u WHERE u.email=:emailValue AND u.phone=:phoneValue", User.class).
                setParameter("emailValue", email).
                setParameter("phoneValue", phone).
                getResultList();