掌握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. 【SQLSERVER】MD5注意事项

    sql中使用MD5加密是很常见的事情,但是不知道注意点的人还是会即便是拷贝网络上的写法也是会出现错误的. 举个例子简单说明: 由上图我们可以发现相同的字符串但是得到的MD5加密的字符却是不相同的,那么 ...

  2. cmd执行调用打开文件

    Process p = new Process();//新进程 p.StartInfo.FileName = "cmd.exe";//打开cmd程序 p.StartInfo.Use ...

  3. Spark中常用的算法

    Spark中常用的算法: 3.2.1 分类算法 分类算法属于监督式学习,使用类标签已知的样本建立一个分类函数或分类模型,应用分类模型,能把数据库中的类标签未知的数据进行归类.分类在数据挖掘中是一项重要 ...

  4. [AHOI 2008] 聚会

    [题目链接] https://www.lydsy.com/JudgeOnline/problem.php?id=1832 [算法] 最近公共祖先 [代码] #include<bits/stdc+ ...

  5. [CF1139 E] Maximize Mex 解题报告 (二分图匹配)

    interlinkage: https://codeforces.com/contest/1139/problem/E description: 有$n$个学生,$m$个社团,每个学生有一个能力值,属 ...

  6. 使用autofac在mvc5下依赖注入

    把遇到的问题汇总一下: 一.安装mvc5版本 命令:pm> Install-Package Autofac 结果安装的Autofac.Integration.Mvc(版本为4.0),所引用的依赖 ...

  7. Arduino-IIC-Wire.h

    前言:Wire.h是Arduino的IIC库. 一.Wire库函数 Wire.begin() Wire.requestFrom() Wire.beginTransmission() Wire.endT ...

  8. 如何在C#中运行数学表达式字符串

    方法1:利用DataTable中的Compute方法 1 string expression = "1+2*3"; 2 DataTable eval = new DataTable ...

  9. JAVA课设——中药古籍《太平圣惠方》数据处理与分析系统

    一.配置JAVA环境 本次课设是在Windows 10(64bit)平台上实现的,所以首先得配置下JAVA环境. 步骤一:先下载一个JDK(1.7)安装包,安装好JDK: 步骤二:JDK环境配置(由于 ...

  10. ES6变量的解构赋值

    变量的解构赋值 1.数组的解构赋值 2.对象的解构赋值 3.字符串的解构赋值 4.数值和布尔值的解构赋值 5.函数参数的解构赋值 6.圆括号问题 7.用途 1.数组的解构赋值 ES6 允许写成下面这样 ...