View
51
Download
5
Category
Preview:
Citation preview
12/3/13 IBatis (MyBatis): Working with Dynamic Queries (SQL) : Loiane Groner
loianegroner.com/2011/03/ibatis-mybatis-working-with-dynamic-queries-sql/ 1/12
Loiane Groner
My development notes
Home
ContactAbout Me
ExtJS PluginsPagingToolbarResizer
Enter Search Terms search
Welcome to Loiane Groner
IBatis (MyBatis): Working withDynamic Queries (SQL)
March 22, 2011 | By Loiane | Add a Comment
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: Mybatis, MySQL conector and JUnit (for testing)
This is how your project should look like:
12/3/13 IBatis (MyBatis): Working with Dynamic Queries (SQL) : Loiane Groner
loianegroner.com/2011/03/ibatis-mybatis-working-with-dynamic-queries-sql/ 2/12
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.
12/3/13 IBatis (MyBatis): Working with Dynamic Queries (SQL) : Loiane Groner
loianegroner.com/2011/03/ibatis-mybatis-working-with-dynamic-queries-sql/ 3/12
The goal of this tutorial is to demonstrate how to retrieve the article information from databaseusing dynamic sql to filter the data.
2 – Article Mapper – XML
One of the most powerful features of MyBatis has always been its DynamicSQL capabilities. If you have any experience with JDBC or any similar
framework, you understand how painful it is to conditionally concatenate stringsof SQL together, making sure not to forget spaces or to omit a comma at theend 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 certainlyimproves 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 orany similar XML based text processors. In previous versions of MyBatis, there
were a lot of elements to know and understand. MyBatis 3 greatly improvesupon this, and now there are less than half of those elements to work with.
MyBatis employs powerful OGNL based expressions to eliminate most of theother elements.
ifchoose (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 weare going to implement a condition (if):
123456789
<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>
?
Related Searches:
Flash Video
PHP Content
Management
Systems
David Mercer
Flash CS3
Best Open Source
CMS
Object-Oriented
Programming With
PHP5
Free CMS Software
Flash Components
CMS Systems
CMS Software
?
12/3/13 IBatis (MyBatis): Working with Dynamic Queries (SQL) : Loiane Groner
loianegroner.com/2011/03/ibatis-mybatis-working-with-dynamic-queries-sql/ 4/12
2 – Second scenario: Now we have two optional filters: article title and author. The user canspecify both, none or only one filter. So we are going to implement two conditions:
3 – Third scenario: Now we want to give the user only one option: the user will have tospecify 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:
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.
123456789101112
<select id="selectArticleByTitleAndAuthor" parameterType 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>
1234567891011121314151617
<select id="selectArticleByTitleOrAuthorOrCategory" parameterType="com.loiane.model.Article" resultType= 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>
1234567891011
<select id="selectArticleByTitleAndAuthor" parameterType 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>
?
?
?
12/3/13 IBatis (MyBatis): Working with Dynamic Queries (SQL) : Loiane Groner
loianegroner.com/2011/03/ibatis-mybatis-working-with-dynamic-queries-sql/ 5/12
What if both title and author are null? We are going to have the following statement:
And what if only the author is not null? We are going to have the fololwing statement:
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:
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 contentreturned 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:
12 </select>
123
SELECT id, title, authorFROM articleWHERE
1234
SELECT id, title, authorFROM articleWHEREAND author LIKE #{author}
12345678910111213
<select id="selectArticleByTitleAndAuthorDynamic" parameterType 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>
123456
<select id="selectArticleByTitleAndAuthorDynamic2" parameterType resultType="Article"> SELECT id, title, author FROM article <trim prefix="WHERE" prefixOverrides="AND |OR "> <if test="title != null">
?
?
?
?
12/3/13 IBatis (MyBatis): Working with Dynamic Queries (SQL) : Loiane Groner
loianegroner.com/2011/03/ibatis-mybatis-working-with-dynamic-queries-sql/ 6/12
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:
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 accidentallyappend 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:
78910111213
title LIKE #{title} </if> <if test="author != null"> AND author LIKE #{author} </if> </trim></select>
123456789
<select id="selectArticleByListCategories" resultType="Article" SELECT id, title, author FROM article WHERE id_category IN <foreach item="category" index="index" collection="list" separator="," close=")"> #{category} </foreach></select>
1234567891011
<?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
?
?
12/3/13 IBatis (MyBatis): Working with Dynamic Queries (SQL) : Loiane Groner
loianegroner.com/2011/03/ibatis-mybatis-working-with-dynamic-queries-sql/ 7/12
1213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
WHERE id_status = 1 <if test="title != null"> AND title LIKE #{title} </if> </select> <select id="selectArticleByTitleAndAuthor" parameterType 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" 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 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 resultType="Article"> SELECT id, title, author FROM article <trim prefix="WHERE" prefixOverrides="AND |OR ">
12/3/13 IBatis (MyBatis): Working with Dynamic Queries (SQL) : Loiane Groner
loianegroner.com/2011/03/ibatis-mybatis-working-with-dynamic-queries-sql/ 8/12
Download
If you want to download the complete sample project, you can get it from my GitHubaccount: 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!
Post to Delicious
22
2
2
68697071727374757677787980818283848586
<if test="title != null"> title LIKE #{title} </if> <if test="author != null"> AND author LIKE #{author} </if> </trim> </select> <select id="selectArticleByListCategories" resultType SELECT id, title, author FROM article WHERE id_category IN <foreach item="category" index="index" collection open="(" separator="," close=")"> #{category} </foreach> </select></mapper>
You may also like:
12/3/13 IBatis (MyBatis): Working with Dynamic Queries (SQL) : Loiane Groner
loianegroner.com/2011/03/ibatis-mybatis-working-with-dynamic-queries-sql/ 9/12
Filed in: iBatis (MyBatis) | Tags: choose, database, dynamic sql, forEach, iBatis, if, Java,MyBatis, mySQL, trim, where
0 comments
Start the discussion…
Best Community Login Share
No one has commented yet.
Subs cribe Add Dis qus to your s i te
0
« IBatis (MyBatis): Discriminator Column Example – Inheritance Mapping Tutorial
IBatis (MyBatis): Working with Stored Procedures »
My Books!
Tutorial: Adding a Flash file inside
an ExtJS 4 Component
ExtJS 4: How to add Tooltip to
Grid Header
Jetty and Eclipse Integration in 3
Steps
Sun Tech Days BrazilPresentations
SUN TECH DAYSBRAZILPRESENTATIONS
How to Populate Ext JSComboBox using Spring
Controller
ExtJS Documentation: How toView it Offline and UX
Documentation
12/3/13 IBatis (MyBatis): Working with Dynamic Queries (SQL) : Loiane Groner
loianegroner.com/2011/03/ibatis-mybatis-working-with-dynamic-queries-sql/ 10/12
Connect
Connect with us on the following social media platforms.
12/3/13 IBatis (MyBatis): Working with Dynamic Queries (SQL) : Loiane Groner
loianegroner.com/2011/03/ibatis-mybatis-working-with-dynamic-queries-sql/ 11/12
Privacy
Ext JS 3.0 Cookbook
Jorge Ramon (P aperback - O c t 20 , …
$47.49
Learning Ext JS 3.2
Shea Frederick, C olin Ramsay, Stev…
$40.49
Ext JS in Action
Jesus Garc ia (P aperback - Dec 5 , 2…
$33.11
Learning Java
Patrick N iemeyer, Jonathan Knudse…
$0.10
Spring Recipes: A Problem-Solu…
Gary Mak, Daniel Rubio, Josh Long (…
$32.49
Loiane Groner - Blog
+ 628
Follow +1
Buy me a coffee!
Do you like this blog? Feel free to donate 1 dollar - or any amount you want! :)
I Recommend
1 2 >
Find us on Facebook
Loiane Groner
3,455 people like Loiane Groner.
Facebook social plugin
Like
12/3/13 IBatis (MyBatis): Working with Dynamic Queries (SQL) : Loiane Groner
loianegroner.com/2011/03/ibatis-mybatis-working-with-dynamic-queries-sql/ 12/12
Categories
Select Category
Loiane Groner
ContactAbout Me
ExtJS Plugins
© 2013 Loiane Groner | All rights reserved.
Recommended