Sometimes, static SQL queries may not be sufficient for application requirements. We may have to build queries dynamically, based on some criteria.
For example, in web applications there could be search screens that provide one or more input options and perform searches based on the chosen criteria. While implementing this kind of search functionality, we may need to build a dynamic query based on the selected options. If the user provides any value for input criteria, we'll need to add that field in the WHERE clause of the query.

MyBatis provides first-class support for building dynamic SQL queries using elements such as <if>, <choose>, <where>, <foreach>, and <trim>.

The If condition

The <if> element can be used to conditionally embed SQL snippets. If the test condition is evaluated to true, then only the SQL snippet will be appended to the query.

Assume we have a Search Courses Screen that has a Tutor dropdown, the CourseName text field, and the StartDate and End Date input fields as the search criteria.

Assume that Tutor is a mandatory field and that the rest of the fields are optional.

When the user clicks on the search button, we need to display a list of courses that meet the following criteria:

  • Courses by the selected Tutor
  • Courses whose name contain the entered course name; if nothing has been provided, fetch all the courses
  • Courses whose start date and end date are in between the provided StartDate and EndDate input fields

We can create the mapped statement for searching the courses as follows:

<resultMap type="Course" id="CourseResult">
<id column="course_id" property="courseId"/>
<result column="name" property="name"/>
<result column="description" property="description"/>
<result column="start_date" property="startDate"/>
<result column="end_date" property="endDate"/>
</resultMap>
<select id="searchCourses" parameterType="hashmap" resultMap="CourseResult">
<![CDATA[
SELECT * FROM COURSES WHERE TUTOR_ID = #{tutorId}
<if test="courseName != null">
AND NAME LIKE #{courseName}
</if>
<if test="startDate != null">
AND START_DATE >= #{startDate}
</if>
<if test="endDate != null">
AND END_DATE <= #{endDate}
</if>
]]>
</select>
public interface CourseMapper {
List<Course> searchCourses(Map<String, Object> map);
} public void searchCourses() {
Map<String, Object> map = new HashMap<String, Object>();
map.put("tutorId", 1);
map.put("courseName", "%java%");
map.put("startDate", new Date());
CourseMapper mapper = sqlSession.getMapper(CourseMapper.class);
List<Course> courses = mapper.searchCourses(map);
for (Course course : courses) {
System.out.println(course);
}
}

This will generate the query SELECT * FROM COURSES WHERE TUTOR_ID= ? AND NAME like ? AND START_DATE >= ?. This will come in handy while preparing a dynamic SQL query based on the given criteria.

MyBatis uses OGNL (Object Graph Navigation Language) expressions for building dynamic queries.

The choose, when, and otherwise conditions

Sometimes, search functionality could be based on the search type. First, the user needs to choose whether he wants to search by Tutor or Course Name or Start Dates and End Dates, and then based on the selected search type, the input field will appear. In such scenarios, we should apply only one of the conditions. MyBatis provides the <choose> element to support this kind of dynamic SQL preparation.

Now let us write a SQL mapped statement to get the courses by applying the search criteria. If no search criteria is selected, the courses starting from today onwards should be fetched as follows:

<select id="searchCourses" parameterType="hashmap" resultMap="CourseResult">
SELECT * FROM COURSES
<choose>
<when test="searchBy == 'Tutor'">
WHERE TUTOR_ID= #{tutorId}
</when>
<when test="searchBy == 'CourseName'">
WHERE name like #{courseName}
</when>
<otherwise>
WHERE TUTOR start_date &gt;= now()
</otherwise>
</choose>
</select>

MyBatis evaluates the <choose> test conditions and uses the clause with the first condition that evaluates to TRUE. If none of the conditions are true, the <otherwise> clause will be used.

The where condition

At times, all the search criteria might be optional. In cases where at least one of the search conditions needs to be applied, then only the WHERE clause should be appended. Also, we need to append AND or OR to the conditions only if there are multiple conditions. MyBatis provides the <where> element to support building these kinds of dynamic SQL statements.

In the example Search Courses screen, we assume that all the search criteria is optional. So, the WHERE clause should be there only if any of the search criteria has been provided.

<select id="searchCourses" parameterType="hashmap" resultMap="CourseResult">
SELECT * FROM COURSES
<where>
<if test=" tutorId != null ">
TUTOR_ID= #{tutorId}
</if>
<if test="courseName != null">
AND name like #{courseName}
</if>
<if test="startDate != null">
AND start_date &gt;= #{startDate}
</if>
<if test="endDate != null">
AND end_date &lt;= #{endDate}
</if>
</where>
</select>

The <where> element inserts WHERE only if any content is returned by the inner conditional tags. Also, it removes the AND or OR prefixes if the WHERE clause begins with AND or OR.

In the preceding example, if none of the <if> conditions are True, <where> won't insert the WHERE clause. If at least one of the <if> conditions is True, <where> will insert the WHERE clause followed by the content returned by the <if> tags.

If the tutor_id parameter is null and the courseName parameter is not null, <where> will take care of stripping out the AND prefix and adding NAME like #{courseName}.

The trim condition

The <trim> element works similar to <where> but provides additional flexibility on what prefix/suffix needs to be prefixed/suffixed and what prefix/suffix needs to be stripped off.

<select id="searchCourses" parameterType="hashmap" resultMap="CourseResult">
SELECT * FROM COURSES
<trim prefix="WHERE" prefixOverrides="AND | OR">
<if test="tutorId != null">
TUTOR_ID= #{tutorId}
</if>
<if test="courseName != null">
AND name like #{courseName}
</if>
</trim>
</select>

Here <trim> will insert WHERE if any of the <if> conditions are true and remove the AND or OR prefixes just after WHERE.

The foreach loop

Another powerful dynamic SQL builder tag is <foreach>. It is a very common requirement for iterating through an array or list and for building AND/OR conditions or an IN clause.

Suppose we want to find out all the courses taught by the tutors whose tutor_id IDs are 1, 3, and 6. We can pass a list of tutor_id IDs to the mapped statement and build a dynamic query by iterating through the list using <foreach>.

<select id="searchCoursesByTutors" parameterType="map" resultMap="CourseResult">
SELECT * FROM COURSES
<if test="tutorIds != null">
<where>
<foreach item="tutorId" collection="tutorIds">
OR tutor_id=#{tutorId}
</foreach>
</where>
</if>
</select>
public interface CourseMapper {
List<Course> searchCoursesByTutors(Map<String, Object> map);
} public void searchCoursesByTutors() {
Map<String, Object> map = new HashMap<String, Object>();
List<Integer> tutorIds = new ArrayList<Integer>();
tutorIds.add(1);
tutorIds.add(3);
tutorIds.add(6);
map.put("tutorIds", tutorIds);
CourseMapper mapper =
sqlSession.getMapper(CourseMapper.class);
List<Course> courses = mapper.searchCoursesByTutors(map);
for (Course course : courses) {
System.out.println(course);
}
}

Let us see how to use <foreach> to generate the IN clause:

<select id="searchCoursesByTutors" parameterType="map" resultMap="CourseResult">
SELECT * FROM COURSES
<if test="tutorIds != null">
<where>
tutor_id IN
<foreach item="tutorId" collection="tutorIds" open="(" separator="," close=")">
#{tutorId}
</foreach>
</where>
</if>
</select>

The set condition

The <set> element is similar to the <where> element and will insert SET if any content is returned by the inner conditions.

<update id="updateStudent" parameterType="Student">
update students
<set>
<if test="name != null">name=#{name},</if>
<if test="email != null">email=#{email},</if>
<if test="phone != null">phone=#{phone},</if>
</set>
where stud_id=#{id}
</update>

Here, <set> inserts the SET keyword if any of the <if> conditions return text and also strips out the tailing commas at the end.

In the preceding example, if phone != null, <set> will take care of removing the comma after phone=#{phone}.

MyBatis(3.2.3) - Dynamic SQL的更多相关文章

  1. Can I use MyBatis to generate Dynamic SQL without executing it?

    Although MyBatis was designed to execute the query after it builds it, you can make use of it's conf ...

  2. mybatis Dynamic SQL

    reference: http://www.mybatis.org/mybatis-3/dynamic-sql.html Dynamic SQL One of the most powerful fe ...

  3. Spring mybatis源码篇章-NodeHandler实现类具体解析保存Dynamic sql节点信息

    前言:通过阅读源码对实现机制进行了解有利于陶冶情操,承接前文Spring mybatis源码篇章-XMLLanguageDriver解析sql包装为SqlSource SqlNode接口类 publi ...

  4. mybatis-3 Dynamic SQL

    Dynamic SQL One of the most powerful features of MyBatis has always been its Dynamic SQL capabilitie ...

  5. Spring mybatis源码篇章-动态SQL基础语法以及原理

    通过阅读源码对实现机制进行了解有利于陶冶情操,承接前文Spring mybatis源码篇章-Mybatis的XML文件加载 前话 前文通过Spring中配置mapperLocations属性来进行对m ...

  6. Mybatis基于接口注解配置SQL映射器(二)

    Mybatis之增强型注解 MyBatis提供了简单的Java注解,使得我们可以不配置XML格式的Mapper文件,也能方便的编写简单的数据库操作代码.但是注解对动态SQL的支持一直差强人意,即使My ...

  7. [转]Dynamic SQL & Stored Procedure Usage in T-SQL

    转自:http://www.sqlusa.com/bestpractices/training/scripts/dynamicsql/ Dynamic SQL & Stored Procedu ...

  8. MyBatis学习总结_11_MyBatis动态Sql语句

    MyBatis中对数据库的操作,有时要带一些条件,因此动态SQL语句非常有必要,下面就主要来讲讲几个常用的动态SQL语句的语法 MyBatis中用于实现动态SQL的元素主要有: if choose(w ...

  9. MyBatis学习 之 二、SQL语句映射文件(2)增删改查、参数、缓存

    目录(?)[-] 二SQL语句映射文件2增删改查参数缓存 select insert updatedelete sql parameters 基本类型参数 Java实体类型参数 Map参数 多参数的实 ...

随机推荐

  1. mongodb基础系列——数据库查询数据返回前台JSP(二)

    上篇博客论述了,数据库查询数据返回前台JSP.博客中主要使用Ajax调用来显示JSON串,来获取其中某一个字段,赋给界面中的某一个控件. 那这篇博客中,我们讲解,把后台List传递JSP展示. Lis ...

  2. UVA 624 - CD (01背包 + 打印物品)

    题目链接:https://uva.onlinejudge.org/index.php?option=com_onlinejudge&Itemid=8&page=show_problem ...

  3. 利用WPF创建含多种交互特性的无边框窗体

    咳咳,标题一口气读下来确实有点累,让我先解释一下.另外文章底部有演示程序的下载. 本文介绍利用WPF创建一个含有以下特性的窗口: 有窗口阴影,比如QQ窗口外围只有几像素的阴影: 支持透明且无边框,为了 ...

  4. MFC 视图、文档、框架(通讯)

    CMainFrame * pMainWnd=(CMainFrame*)AfxGetApp()->m_pMainWnd;//主框架 CChildFrame * pChild = (CChildFr ...

  5. cocos2d 制作动态光晕效果基础 —— blendFunc

    转自:http://blog.csdn.net/yang3wei/article/details/7795764 最近的项目要求动态光晕的效果. 何谓动态光晕?之前不知道别人怎么称呼这个效果, 不过在 ...

  6. 数据字符集mysql主从数据库,分库分表等笔记

    文章结束给大家来个程序员笑话:[M] 1.mysql的目录:在rpm或者yum安装时:/var/lib/mysql  在编译安装时默许目录:/usr/local/mysql 2.用rpm包安装的MyS ...

  7. QM课程02-外部功能

    质量计划 · 对质量计划和检验计划进行基本数据的管理 · 物料说明 · 检验计划 质量检验 · 触发检验 · 具有检验计划选择和样本计算的检验处理 · 打印采样和检验的车间文档 · 记录结果和缺陷 · ...

  8. CDOJ 486 Good Morning 傻逼题

    Good Morning Time Limit: 20 Sec Memory Limit: 256 MB 题目连接 http://acm.uestc.edu.cn/#/problem/show/486 ...

  9. delphi 插入表格HTML代码

     <table width="174"  height="76" border="1" align="center" ...

  10. 【转】DLX 精确覆盖 重复覆盖

    问题描述: 给定一个n*m的矩阵,有些位置为1,有些位置为0.如果G[i][j]==1则说明i行可以覆盖j列. Problem: 1)选定最少的行,使得每列有且仅有一个1. 2)选定最少的行,使得每列 ...