Search code examples
javahibernatejpahqlentitymanager

hibernate parameter with that name [<name>] did not exist


I am running the following code.

UserService.java

String alias = "u";
String select = "SELECT u.email";
String where = "u.userId = :id";
Map<String, Object> params = new HashMap<>();
params.put("id", userId);

List<User> users = db.findRecords(User.class, alias, select, where, params);

DB.java

public <T> List<T> findRecords(Class<T> entityClass, String entityAlias, String select, String where, Map<String, Object> params) {
    String sql = select + " FROM " + entityClass.getName() + " " + entityAlias;

    if (where != null) {
        sql = sql + " WHERE " + where;
    }

    Query query = entityManager.createQuery(sql);
    System.out.println(sql);
    if (!params.isEmpty()) {
        Iterator<Entry<String, Object>> iterator = params.entrySet().iterator();
        while (iterator.hasNext()) {
            Entry<String, Object> entry = iterator.next();
            System.out.println("key: " + entry.getKey() + ", value: " + entry.getValue());
            query.setParameter((String) entry.getKey(), (Long) entry.getValue());
        }
    }

    return query.getResultList();
}

I am getting the following error log.

SELECT u.email FROM com.catalog.user.User u WHERE u.userId = :id
key: id, value: 28636907

Caused by: java.lang.IllegalArgumentException: Parameter with that name [id] did not exist

If the parameter is getting printed in the console then what is causing the illegal arguments exception to come up?

Please help!


Solution

  • 1) check that it is not a typo in the parameter name :id. It's case sensitive.

    2) try to execute query without parameters. It might be a problem in the entity mapping.

    3) try to set parameter directly in the query without HashMap.