Tag Archives: java

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 + '%');

I18n workaround for Spring form:options tag

Spring Framework provides the convenient form:options tag to render a list of <option> tags for a form <select>. Here is an example:

<form:select id="status" path="status" cssClass="text large" cssErrorClass="text large error" >
    <form:options items="${statusList}" itemValue="id" itemLabel="label"></form:options>
</form:select>

It does iteratate through statusList and will output each item as an option with the value statusList[i].id and the text statusList[i].label and automatically make the option corresponding to status selected.

Unfortunately form:options does not support i18n (internationalization), which make it in some cases rather worthless. I18n support is currently scheduled for inclusion in 3.0 M1.

To support internationalization we have to do a workaround that is somewhat more clunky:

<select id="status" name="status" class="text large">
  <c:set var="currentStatus">${currentStatus}</c:set>
  <c:forEach var="status" items="${statusList}">
    <c:choose>
      <c:when test="${status == currentStatus}">
        <option value="${status.id}" selected><fmt:message key="status.${status.label}"/></option>
      </c:when>
      <c:otherwise>
        <option value="${status.id}"><fmt:message key="status.${status.label} quot;/></option>
      </c:otherwise>
    </c:choose>
  </c:forEach>
</select>