MyBatis中动态SQL元素的使用
掌握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种情况。
- 如果传入的是单参数且参数类型是一个List的时候,collection属性值为list
- 如果传入的是单参数且参数类型是一个array数组的时候,collection的属性值为array
- 如果传入的参数是多个的时候,我们就需要把它们封装成一个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元素的使用的更多相关文章
- Mybatis中动态SQL多条件查询
Mybatis中动态SQL多条件查询 mybatis中用于实现动态SQL的元素有: if:用if实现条件的选择,用于定义where的字句的条件. choose(when otherwise)相当于Ja ...
- Mybatis中动态SQL语句中的parameterType不同数据类型的用法
Mybatis中动态SQL语句中的parameterType不同数据类型的用法1. 简单数据类型, 此时#{id,jdbcType=INTEGER}中id可以取任意名字如#{a,jdbcType ...
- MyBatis中动态SQL语句完成多条件查询
一看这标题,我都感觉到是mybatis在动态SQL语句中的多条件查询是多么的强大,不仅让我们用SQL语句完成了对数据库的操作:还通过一些条件选择语句让我们SQL的多条件.动态查询更加容易.简洁.直观. ...
- mybatis中动态SQL之trim详解
一. 背景 之前mybatis中<where>.<update>.<if>.<foreach>标签用的多,知道有<trim>这个标签,但很少 ...
- 阶段3 1.Mybatis_08.动态SQL_03.mybatis中动态sql语句-foreach和sql标签
foreach标签 in的查询 sql语句好写,但是传参在映射文件里面改怎么传呢 定义一个List<Integer>成员变量,然后生成get和set 定义一个新的查询方法 open:开始符 ...
- 阶段3 1.Mybatis_08.动态SQL_02.mybatis中动态sql语句-where标签的使用
这里的userSex是实体类里面的属性名,而不是数据库内的字段名称 一个老王改成性别女,为了区分一下 增加sex字段的查询 where标签 用上where和刚才的执行效果是一样的 where标签使我们 ...
- mybatis中的.xml文件总结——mybatis的动态sql
resultMap resultType可以指定pojo将查询结果映射为pojo,但需要pojo的属性名和sql查询的列名一致方可映射成功. 如果sql查询字段名和pojo的属性名不一致,可以通过re ...
- MyBatis的动态SQL详解
MyBatis的动态SQL是基于OGNL表达式的,它可以帮助我们方便的在SQL语句中实现某些逻辑,本文详解mybatis的动态sql,需要的朋友可以参考下 MyBatis 的一个强大的特性之一通常是它 ...
- Mybatis解析动态sql原理分析
前言 废话不多说,直接进入文章. 我们在使用mybatis的时候,会在xml中编写sql语句. 比如这段动态sql代码: <update id="update" parame ...
随机推荐
- redhat gitlab的搭建
http://www.cnblogs.com/derekchen/p/5870723.html 1.新建 /etc/yum.repos.d/gitlab-ce.repo,添加以下内容 [gitlab- ...
- selenium实例学习地址
一个完整的maven配置selenium webdriver工程实例 http://www.spasvo.com/ceshi/open/kygncsgj/Selenium/201312209580 ...
- EularProject 36:2进制和10进制回文数
华电北风吹 天津大学认知计算与应用重点实验室 完毕日期:2015/7/29 Double-base palindromes Problem 36 The decimal number, 585 = 1 ...
- Could not read from remote repository.
今天换新电脑,忘了配置git环境,就去gitserver上代替码.然后一直报错,后来就又一次配置了git环境.步骤例如以下 damingwuage:Desktop damingwuage$ ssh-k ...
- Vue环境搭建+VSCode+Win10
一.安装Node.js(js的运行环境) 1.在Node.js官网https://nodejs.org/en/download/下载安装包.2.下载后进行安装.3.打开命令行,输入node -v可以查 ...
- spark 决策树分类算法demo
分类(Classification) 下面的例子说明了怎样导入LIBSVM 数据文件,解析成RDD[LabeledPoint],然后使用决策树进行分类.GINI不纯度作为不纯度衡量标准并且树的最大深度 ...
- 自己实现的一个 .net 缓存类(原创)
public class CacheContainer { private static Hashtable ht = new Hashtable(); /// <summary> /// ...
- x64汇编第三讲,64位调用约定与函数传参.
目录 x64汇编第三讲,64位调用约定与函数传参. 一丶复习X86传参 二丶x64汇编 2.1汇编详解 x64汇编第三讲,64位调用约定与函数传参. 一丶复习X86传参 在x86下我们汇编的传参如下: ...
- kubernetes系列
目录: 介绍的全部可以在github上找到,链接 haoprogrammer kubernetes学习:(一).kubeadm搭建kubernetes(v1.13.1)单节点集群 kubernete ...
- iOS怎么判断字典中存在nil值
遍历字典中的key,然后根据key值取出对应的value如:for (NSString *key in dict) { //处理字典的键值 NSString *value = dict[key]; i ...