SQL Zone is brought to you in partnership with:

Loiane Groner, Brazilian, works as a Java/ Sencha evangelist. She has 7+ years of experience in web development. She is the ESJUG (Espirito Santo Java Users Group) and CampinasJUG (Campinas Java Users Group) leader and coordinator. Loiane is passionate about technology and programming. Also author of ExtJS 4 First Look book. Loiane is a DZone MVB and is not an employee of DZone and has posted 42 posts at DZone. You can read more from them at their website. View Full User Profile

IBatis (MyBatis): Working with Dynamic Queries (SQL)

03.23.2011
| 25916 views |
  • submit to reddit

This tutorial will walk you through how to setup iBatis (MyBatis) in a simple Java project and will present how to work with dynamic queries (SQL).

Pre-Requisites

For this tutorial I am using:

IDE: Eclipse (you can use your favorite one)
DataBase: MySQL
Libs/jars: MybatisMySQL conector and JUnit (for testing)

This is how your project should look like:

Sample Database

Please run the script into your database before getting started with the project implementation. You will find the script (with dummy data) inside the sql folder.

1 – Article POJO

I represented the pojo we are going to use in this tutorial with a UML diagram, but you can download the complete source code in the end of this article.

The goal of this tutorial is to demonstrate how to retrieve the article information from database using dynamic sql to filter the data.

2 – Article Mapper – XML

One of the most powerful features of MyBatis has always been its Dynamic SQL capabilities. If you have any experience with JDBC or any similar framework, you understand how painful it is to conditionally concatenate strings of SQL together, making sure not to forget spaces or to omit a comma at the end of a list of columns. Dynamic SQL can be downright painful to deal with.

While working with Dynamic SQL will never be a party, MyBatis certainly improves the situation with a powerful Dynamic SQL language that can be used within any mapped SQL statement.

The Dynamic SQL elements should be familiar to anyone who has used JSTL or any similar XML based text processors. In previous versions of MyBatis, there were a lot of elements to know and understand. MyBatis 3 greatly improves upon this, and now there are less than half of those elements to work with. MyBatis employs powerful OGNL based expressions to eliminate most of the other elements.

  • if
  • choose (when, otherwise)
  • trim (where, set)
  • foreach

Let’s explain each one with examples.

1 – First scenario: we want to retrieve all the articles from database with an optional filter: title. In other words, if user specify an article title, we are going to retrieve the articles that match with the title, otherwise we are going to retrieve all the articles from database. So we are going to implement a condition (if):

<select id="selectArticleByTitle" parameterType="com.loiane.model.Article"
resultType="Article">
SELECT id, title, author
FROM article
WHERE id_status = 1
<if test="title != null">
AND title LIKE #{title}
</if>
</select>

2 – Second scenario: Now we have two optional filters: article title and author. The user can specify both, none or only one filter. So we are going to implement two conditions:

<select id="selectArticleByTitleAndAuthor" parameterType="com.loiane.model.Article"
resultType="Article">
SELECT id, title, author
FROM article
WHERE id_status = 1
<if test="title != null">
AND title LIKE #{title}
</if>
<if test="author != null">
AND author LIKE #{author}
</if>
</select>

3 – Third scenario: Now we want to give the user only one option: the user will have to specify only one of the following filters: title, author or retrieve all the articles from iBatis category. So we are going to use a Choose element:

<select id="selectArticleByTitleOrAuthorOrCategory"
parameterType="com.loiane.model.Article" resultType="Article">
SELECT id, title, author
FROM article
WHERE id_status = 1
<choose>
<when test="title != null">
AND title LIKE #{title}
</when>
<when test="author != null">
AND author LIKE #{author}
</when>
<otherwise>
AND id_category = 3
</otherwise>
</choose>
</select>

4 – Fourth scenario: take a look at all three statements above. They all have a condition in common: WHERE id_status = 1. It means we are already filtering the active articles Let’s remove this condition to make it more interesting.

<select id="selectArticleByTitleAndAuthor" parameterType="com.loiane.model.Article"
resultType="Article">
SELECT id, title, author
FROM article
WHERE
<if test="title != null">
title LIKE #{title}
</if>
<if test="author != null">
AND author LIKE #{author}
</if>
</select>

What if both title and author are null? We are going to have the following statement:

SELECT id, title, author
FROM article
WHERE

And what if only the author is not null? We are going to have the fololwing statement:

SELECT id, title, author
FROM article
WHERE
AND author LIKE #{author}

And both FAILS!

How to fix it?

5 – Fifth scenario: we want to retrieve all the articles with two optional filters: title and author. To avoid the 4th scenatio, we are going to use a Where element:

<select id="selectArticleByTitleAndAuthorDynamic" parameterType="com.loiane.model.Article"
resultType="Article">
SELECT id, title, author
FROM article
<where>
<if test="title != null">
title LIKE #{title}
</if>
<if test="author != null">
AND author LIKE #{author}
</if>
</where>
</select>

MyBatis has a simple answer that will likely work in 90% of the cases. And in cases where it doesn’t, you can customize it so that it does.

The where element knows to only insert “WHERE” if there is any content returned by the containing tags. Furthermore, if that content begins with “AND” or “OR”, it knows to strip it off.

If the where element does not behave exactly as you like, you can customize it by defining your own trim element. For example,the trim equivalent to the where element is:

<select id="selectArticleByTitleAndAuthorDynamic2" parameterType="com.loiane.model.Article"
resultType="Article">
SELECT id, title, author
FROM article
<trim prefix="WHERE" prefixOverrides="AND |OR ">
<if test="title != null">
title LIKE #{title}
</if>
<if test="author != null">
AND author LIKE #{author}
</if>
</trim>
</select>

The overrides attribute takes a pipe delimited list of text to override, where whitespace is relevant. The result is the removal of anything specified in the overrides attribute, and the insertion of anything in the with attribute.

You can also use the Trim element with SET.

6 – Sixth scenario: the user will choose all the categories an article can belong to. So in this case, we have a list (a collection), and we have to interate this collection and we are going to use a foreach element:

<select id="selectArticleByTitleAndAuthorDynamic2" parameterType="com.loiane.model.Article"
resultType="Article">
SELECT id, title, author
FROM article
<trim prefix="WHERE" prefixOverrides="AND |OR ">
<if test="title != null">
title LIKE #{title}
</if>
<if test="author != null">
AND author LIKE #{author}
</if>
</trim>
</select>

The foreach element is very powerful, and allows you to specify a collection, declare item and index variables that can be used inside the body of the element. It also allows you to specify opening and closing strings, and add a separator to place in between iterations. The element is smart in that it won’t accidentally append extra separators.

Note: You can pass a List instance or an Array to MyBatis as a parameter object. When you do, MyBatis will automatically wrap it in a Map, and key it by name. List instances will be keyed to the name “list” and array instances will be keyed to the name “array”.

The complete Article.xml file looks like this:

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">

<mapper namespace="Article">

<select id="selectArticleByTitle" parameterType="com.loiane.model.Article"
resultType="Article">
SELECT id, title, author
FROM article
WHERE id_status = 1
<if test="title != null">
AND title LIKE #{title}
</if>
</select>

<select id="selectArticleByTitleAndAuthor" parameterType="com.loiane.model.Article"
resultType="Article">
SELECT id, title, author
FROM article
WHERE id_status = 1
<if test="title != null">
AND title LIKE #{title}
</if>
<if test="author != null">
AND author LIKE #{author}
</if>
</select>

<select id="selectArticleByTitleOrAuthorOrCategory" parameterType="com.loiane.model.Article"
resultType="Article">
SELECT id, title, author
FROM article
WHERE id_status = 1
<choose>
<when test="title != null">
AND title LIKE #{title}
</when>
<when test="author != null">
AND author LIKE #{author}
</when>
<otherwise>
AND id_category = 3
</otherwise>
</choose>
</select>

<select id="selectArticleByTitleAndAuthorDynamic" parameterType="com.loiane.model.Article"
resultType="Article">
SELECT id, title, author
FROM article
<where>
<if test="title != null">
title LIKE #{title}
</if>
<if test="author != null">
AND author LIKE #{author}
</if>
</where>
</select>

<select id="selectArticleByTitleAndAuthorDynamic2" parameterType="com.loiane.model.Article"
resultType="Article">
SELECT id, title, author
FROM article
<trim prefix="WHERE" prefixOverrides="AND |OR ">
<if test="title != null">
title LIKE #{title}
</if>
<if test="author != null">
AND author LIKE #{author}
</if>
</trim>
</select>

<select id="selectArticleByListCategories" resultType="Article">
SELECT id, title, author
FROM article
WHERE id_category IN
<foreach item="category" index="index" collection="list"
open="(" separator="," close=")">
#{category}
</foreach>
</select>
</mapper>

Download

If you want to download the complete sample project, you can get it from my GitHub account: https://github.com/loiane/ibatis-dynamic-sql

If you want to download the zip file of the project, just click on download:

There are more articles about iBatis to come. Stay tooned!

Happy Coding! :)

 

From http://loianegroner.com/2011/03/ibatis-mybatis-working-with-dynamic-queries-sql/

Published at DZone with permission of Loiane Groner, author and DZone MVB.

(Note: Opinions expressed in this article and its replies are the opinions of their respective authors and not those of DZone, Inc.)

Tags:

Comments

Witold Szczerba replied on Wed, 2011/03/23 - 12:51pm

What I am really missing here is the solution for the Don't Repeat Yourself problem.

Look at the example above, imagine you add few fields into Article table. The statement below:

SELECT id, title, author
FROM article

 is repeated so many times. Now you have to add the fields everywhere. What if the SELECT ... FROM ... JOIN contains many fields from many tables. One change in database requires many changes in many statements. Suppose we have dozens or hundreds queries which joins Address table and we have to introduce new field there...

 

Lance Semmens replied on Thu, 2011/03/24 - 6:38am

@witold there is a solution. Please see "Reusing SQL Fragments" at http://ibatis.apache.org/docs/dotnet/datamapper/ch03s03.html#id379227

Jose Maria Arranz replied on Fri, 2011/03/25 - 11:47am in response to: Witold Szczerba

Welcome to the declarative programming way of life.

 

Comment viewing options

Select your preferred way to display the comments and click "Save settings" to activate your changes.