掌握MyBatis中动态SQL元素的使用

  • if
  • choose(when,otherwise)
  • trim
  • where
  • set
  • foreach
  • <SQL>和<include>

在应用中我们经常会做一些动态的拼接条件,但是如果是JDBC我们可以用程序拼接SQL语句,如果MyBatis,我们可以使用动态SQL语句。例如按照员工姓名和工资来搜索员工信息,如果如果姓名和工资的检索值为空,则忽略这个检索条件。一般来说,我们都会用where 1=1类似这种写法来实现,但是MyBatis就需要动态语句实现。

1      if元素

mapper.xml

 <select id="selectStudentByCondition" parameterType="student" resultMap="BaseResultMap">
select * from student where 1=1
<!-- 当传入的属性值为空或者空字符串时会忽略掉条件
注意:test中的pojo中的属性名称
like的使用
<![CDATA[ ]]>的使用-->
<if test="stuName !=null and stuName != ''">
and stu_name like '%' ||#{stuName}||'%'
</if>
<if test="stuBirthdate != null">
<![CDATA[and stu_birthdate>#{stuBirthdate}]]>
</if>
</select>

daoImpl.java

 @Override
public void testQuery6(Student s){
SqlSession session = fac.openSession();
List<Student> result = session.selectList("student.selectStudentByCondition",s);
for (Student s1 : result) {
System.out.println("s1 id=" + s1.getStuId());
System.out.println("s1 name=" + s1.getStuName());
System.out.println("s1 Birthdate=" + s1.getStuBirthdate());
}
session.close();
}

测试

 public static void main(String[] args) throws Exception {
//创建要保存的学生信息
Student s = new Student();
s.setStuName("zhou");
s.setStuBirthdate(new SimpleDateFormat("yyyy-MM-dd").parse("1991-1-12")); StudentDao sdao = new StudentDaoImpl(fac);
sdao.testQuery6(s);
}

2     choose元素

choose元素相当于java语句的if … else if …else语句

 <!-- 动态SQL:choose标签 -->
<select id="queryByCondition2" parameterType="student " resultMap="BaseResultMap">
select * from student where 1=1
<choose>
<when test="stuName != null and stuName != ''">
and stu_name=#{stuName}
</when>
<when test="stuBirthdate != null">
and stu_birthdate=#{stuBirthdate}
</when>
<otherwise>
and stu_phone=#{stuPhone}
</otherwise>
</choose>
</select>

3      WHERE元素

使用where元素会自动根据条件的个数增删where语句and运算符,所以不需要写where 1=1之类的语句

 <!-- 动态SQL:where标签 -->
<select id="queryByCondition3" parameterType="student " resultMap="BaseResultMap">
select * from student
<where>
<if test="stuName != null and stuName != ''">
and stu_name=#{stuName}
</if>
<if test="stuBirthdate != null">
and stu_birthdate=#{stuBirthdate}
</if>
<if test="stuPhone != null and stuPhone != ''">
and stu_phone=#{stuPhone}
</if>
</where>
</select>

4      Trim元素

trim元素的主要功能是可以在自己包含的内容前加上某些前缀,也可以在其后加上某些后缀,与之对应的属性是prefix和suffix;可以把包含内容的首部某些内容覆盖,即忽略,也可以把尾部的某些内容覆盖,对应的属性是prefixOverrides和suffixOverrides

 <!-- 动态SQL:trim标签 -->
<select id="queryByCondition4" parameterType="student " resultMap="BaseResultMap">
select * from student
<trim prefix="where" prefixOverrides="and|or">
<if test="stuName != null and stuName != ''">
and stu_name=#{stuName}
</if>
<if test="stuBirthdate != null">
and stu_birthdate=#{stuBirthdate}
</if>
<if test="stuPhone != null and stuPhone != ''">
or stu_phone=#{stuPhone}
</if>
</trim>
</select>

5      foreach元素

foreach的主要用在构建in条件中,它可以在SQL语句中进行迭代一个集合。foreach元素的属性主要有item,index,collection,open,separator,close。item表示集合中每一个元素进行迭代时的别名,index指定一个名字,用于表示在迭代过程中,每次迭代到的位置,open表示该语句以什么开始,separator表示在每次进行迭代之间以什么符号作为分隔符,close表示以什么结束,在使用foreach的时候最关键的也是最容易出错的就是collection属性,该属性是必须指定的,但是在不同情况下,该属性的值是不一样的,主要有以下3种情况。

  1. 如果传入的是单参数且参数类型是一个List的时候,collection属性值为list
  2. 如果传入的是单参数且参数类型是一个array数组的时候,collection的属性值为array
  3. 如果传入的参数是多个的时候,我们就需要把它们封装成一个Map了,当然单参数也可以封装成map,实际上如果你在传入参数的时候,在MyBatis里面也是会把它封装成一个Map的,map的key就是参数名,所以这个时候collection属性值就是传入的List或array对象在自己封装的map里面的key

Mapper.xml

 <!-- 动态SQL:传入Array数组 -->
<select id="queryByInArray" resultMap="BaseResultMap">
select * from student
<if test="array.length>0">
where stu_id in
<foreach collection="array" index="i" item="stuId" open="(" close=")" separator=",">
#{stuId}
</foreach>
</if>
</select>
<!-- 动态SQL:传入List集合 -->
<select id="queryByInList" resultMap="BaseResultMap">
select * from student
<if test="list.size()>0">
where stu_id in
<foreach collection="list" index="i" item="stuId" open="("
close=")" separator=",">
#{stuId}
</foreach>
</if>
</select>
<!-- 动态SQL:传入Map集合包含List集合 -->
<select id="queryByInMap" resultMap="BaseResultMap">
select * from student
<if test="ids.size()>0">
where stu_id in
<foreach collection="ids" index="i" item="stuId" open="("
close=")" separator=",">
#{stuId}
</foreach>
</if>
</select>

DaoImpl.java

 @Override
public void testQuery7(){
SqlSession session = fac.openSession();
int[] ids = new int[]{2};
List<Student> list = session.selectList("student.queryByInArray",ids);
for (Student item : list) {
System.out.println(item);
}
session.close();
}
@Override
public void testQuery8(){
SqlSession session = fac.openSession();
List ids = new ArrayList();
ids.add(2);
ids.add(3);
ids.add(4);
List<Student> list = session.selectList("student.queryByInList",ids);
for (Student item : list) {
System.out.println(item);
}
session.close();
}
@Override
public void testQuery8(){
SqlSession session = fac.openSession();
List ids = new ArrayList();
ids.add(2);
ids.add(3);
Map map = new HashMap();
map.put("ids", ids);
List<Student> list = session.selectList("student.queryByInMap",map);
for (Student item : list) {
System.out.println(item);
}
session.close();
}

6      set元素

set元素主要是用在更新操作的时候,它的主要功能和where元素其实是差不多的,主要是在包含的语句前输出一个set,然后如果包含的语句是以逗号结束的话将会把该逗号忽略,如果set包含的内容为空的话则会出错。有了set元素我们就可以动态的更新那些修改了的字段。

     <!-- 动态SQL:set更新 -->
<update id="updateByCondition" parameterType="student">
update student
<set>
<if test="stuName!=null and stuName!=''">
stu_name=#{stuName},
</if>
<if test="stuBirthdate!=null">
stu_birthdate=#{stuBirthdate},
</if>
<if test="stuPhone!=null and stuPhone!=''">
stu_phone=#{stuPhone}
</if>
</set>
where stu_id=#{stuId}
</update>

7      <SQL>和<include>

可以编写一些语句片段<SQL>标签,然后在其他语句标签汇中用<include>引用,这样可以是SQL语句片段得到重用

示例:

<!-- SQL片段 -->
<SQL id="SQL_select">
select *
</SQL>
<SQL id="SQL_count">
select count(*)
</SQL> <!-- 包含SQL片段 -->
<select id="query6" resultMap="BaseResultMap">
<include refid="SQL_select"/>
from student
</select> <select id="query7" resultType="java.lang.Integer">
<include refid="SQL_count"/>
from student
</select>

MyBatis中动态SQL元素的使用的更多相关文章

  1. Mybatis中动态SQL多条件查询

    Mybatis中动态SQL多条件查询 mybatis中用于实现动态SQL的元素有: if:用if实现条件的选择,用于定义where的字句的条件. choose(when otherwise)相当于Ja ...

  2. Mybatis中动态SQL语句中的parameterType不同数据类型的用法

    Mybatis中动态SQL语句中的parameterType不同数据类型的用法1. 简单数据类型,    此时#{id,jdbcType=INTEGER}中id可以取任意名字如#{a,jdbcType ...

  3. MyBatis中动态SQL语句完成多条件查询

    一看这标题,我都感觉到是mybatis在动态SQL语句中的多条件查询是多么的强大,不仅让我们用SQL语句完成了对数据库的操作:还通过一些条件选择语句让我们SQL的多条件.动态查询更加容易.简洁.直观. ...

  4. mybatis中动态SQL之trim详解

    一. 背景 之前mybatis中<where>.<update>.<if>.<foreach>标签用的多,知道有<trim>这个标签,但很少 ...

  5. 阶段3 1.Mybatis_08.动态SQL_03.mybatis中动态sql语句-foreach和sql标签

    foreach标签 in的查询 sql语句好写,但是传参在映射文件里面改怎么传呢 定义一个List<Integer>成员变量,然后生成get和set 定义一个新的查询方法 open:开始符 ...

  6. 阶段3 1.Mybatis_08.动态SQL_02.mybatis中动态sql语句-where标签的使用

    这里的userSex是实体类里面的属性名,而不是数据库内的字段名称 一个老王改成性别女,为了区分一下 增加sex字段的查询 where标签 用上where和刚才的执行效果是一样的 where标签使我们 ...

  7. mybatis中的.xml文件总结——mybatis的动态sql

    resultMap resultType可以指定pojo将查询结果映射为pojo,但需要pojo的属性名和sql查询的列名一致方可映射成功. 如果sql查询字段名和pojo的属性名不一致,可以通过re ...

  8. MyBatis的动态SQL详解

    MyBatis的动态SQL是基于OGNL表达式的,它可以帮助我们方便的在SQL语句中实现某些逻辑,本文详解mybatis的动态sql,需要的朋友可以参考下 MyBatis 的一个强大的特性之一通常是它 ...

  9. Mybatis解析动态sql原理分析

    前言 废话不多说,直接进入文章. 我们在使用mybatis的时候,会在xml中编写sql语句. 比如这段动态sql代码: <update id="update" parame ...

随机推荐

  1. maven 自建库

    maven repository 标签: mavenjarxmlserver工具磁盘 2009-11-26 10:56 42322人阅读 评论(7) 收藏 举报   目录(?)[+]   什么是Mav ...

  2. Android进程回收机制LMK(Low Memory Killer)【转】

    本文转载自:http://www.cnblogs.com/wytiger/p/5744752.html 熟悉Android系统的童鞋都知道,系统出于体验和性能上的考虑,app在退到后台时系统并不会真正 ...

  3. Android4.0.4-在build.prop中添加属性的方法【转】

    本文转载自:http://blog.csdn.net/imyfriend/article/details/8939964 1.在*.rc文件中用setprop添加,例如在源码android4.0\sy ...

  4. [JavaEE] 20141228_Java类文章搜集

    http://www.blogjava.net/jiangshachina 博客园java频道 Maven入门--概念与实例(原) Maven入门--较复杂的实例(原) Maven插件使用收集(原) ...

  5. [Plugin] JQuery.uploadify上传文件插件的使用详解For ASP.NET

    URL:http://www.cnblogs.com/xiaopin/archive/2010/01/21/1653523.html 今天下午整理文件上传的例子,感觉收集到的例子都很不人性话,后来找到 ...

  6. BZOJ 4771 主席树+倍增+set

    思路: 因为有深度的限制,并且我们是在线段树上维护权值,所以我们把点按照dep排序,然后一个一个修改...主席树的下标就是dfs序,子树的查询就是区间查询... 但是发现这样怎么去维护LCA呢...因 ...

  7. maven使用杂记

    maven test使用记录 运行指定的测试类:     >mvn test -Dtest=[ClassName] 运行测试类中指定的方法:(这个需要maven-surefire-plugin: ...

  8. 7.Performance Statistics(性能统计)

    利用性能分析器中统计的数据,来分析和发现,其中的性能瓶颈点. 1.设置Statistic Options View>Live Options中的Statistic Options设置可以设置需要 ...

  9. Codeforces Round #446

    Greed #include<stdio.h> #include<string.h> #include<stdlib.h> #include<vector&g ...

  10. [原创]C++带空格字符串的输入问题

    字符串一直是一个重点加难点,很多笔试面试都会涉及,带空格的字符串更是十分常见,现在对字符串的输入问题进行一下总结. C++用cin输入的时候会忽略空格以后的字符,比如 char a[100]; cin ...