Hibernate HQL like query using named parameters

Using the LIKE condition with a “%” sign for pattern matching in a HQL query with named parameters required some tweaking.

This did not work:

String query = "from user u where u.name like %:name%"

getHibernateTemplate().findByNamedParam(query, "name", str);

It resulted in a org.hibernate.QueryException: unexpected char: ‘%’ error.

Next I tried using single quotes:

String query = "from user u where u.name like '%:name%'"

getHibernateTemplate().findByNamedParam(query, "name", str);

Didn’t work either, an org.hibernate.QueryParameterException: could not locate named parameter.

What actually worked was putting the “%” signs in the parameter:

String query = "from user u where u.name like :name"

getHibernateTemplate().findByNamedParam(query, "name", '%' + str + '%');