How to define a SQL Like statement in iBATIS sqlMaps

When utilizing the iBATIS Framework as the persistence layer of your applications, you may get stumped as to why your LIKE statements are not being handled correctly and throws errors. When at first glance the errors have to do with other parameters in the query. The solution to this problem is to program the % character into the parameters passed into the sql statement, and to not have them hard coded into the sqlMap.

Example:

In this example we want to have a query that selects users with a last name like an inputted value. The query for this would be of the following format:

 SELECT * FROM USERS WHERE lastName LIKE "DEN%"

At first glance we may want to try to create our sqlMap statement as:

<select id="selectByName"parameterClass="String" >
    SELECT * FROM USERS WHERE lastName LIKE #value#%
</select>

This however will end up throwing errors. The correct way of creating this statement would be to leave out the % character and simply have the following statement:

<select id="selectByName"parameterClass="String" >
    SELECT * FROM USERS WHERE lastName LIKE #value#
</select>

Doing so will enable the query to function correctly where the % character gets passed in as part of the parameter. This also enables your query to be more dynamic by having the % character in any placement of the variable string.

Resources

// Java // SQL //

Comments & Questions

Add Your Comment