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 ...
随机推荐
- HDU 5218 The E-pang Palace (简单几何—2014广州现场赛)
题目链接:pid=5128">http://acm.hdu.edu.cn/showproblem.php? pid=5128 题面: The E-pang Palace Time Li ...
- leetCode 20.Valid Parentheses (有效的括号) 解题思路和方法
Valid Parentheses Given a string containing just the characters '(', ')', '{', '}', '[' and ']', de ...
- virtualbox 安装虚拟机(centos7) 并映射本地文件夹至虚拟机(增强工具)
一.安装环境 操作系统:windows10 virtualbox: 5.2.20 (在安装virtualbox 时可能需要 进入BIOS 设置虚拟化系统启动) centos7:http://mirro ...
- 从默认析构函数学习c++,new,delete,内存泄漏,野指针
默认析构函数:当系统没有显式定义析构函数,编译器同样会为对象定义一个默认析构函数,默认的析构函数只能释放普通数据成员所占用的空间,无法通过释放通过new和malloc进行申请的空间,因此避免内存泄漏, ...
- postgresql 常规操作以及检查备份
一.建表时,复制源表的信息test=# test=# \d test.t1 Table "test.t1" Column | Type | Collation | Nullable ...
- POJ 1200 Hash
我的hash从来没写对过........ (白学了快一年OI --原来连个hash都没写对过) 但是 但是 今天是一个值得纪念的日子. 看看标题 我竟然在写hash的题解. (好了好了 废话少说) 题 ...
- QlikSense系列(3)——QlikSense建立数据模型
QlikSense管理数据在帮助中写的比较清楚 https://help.qlik.com/zh-CN/sense/3.1/Subsystems/Hub/Content/LoadData/load-d ...
- 洛谷P2455 [SDOI2006]线性方程组(高斯消元)
题目描述 已知n元线性一次方程组. 其中:n<=50, 系数是[b][color=red]整数<=100(有负数),bi的值都是整数且<300(有负数)(特别感谢U14968 mmq ...
- 关于javascript中静态成员和实例成员的详细解释
关于javascript中静态成员和实例成员的详细解释 在我们了解什么是静态成员和实例成员之前,我们首先来了解一下什么是实例? 实例就是由构造函数创建出来的对象. 例如案例中 p 就是实例: fun ...
- linux下的头文件和库文件搜索路径 (转)
GCC 找头文件有三种策略: 1. 会在默认情况下指定到 /usr/include 文件夹 ( 更深层次的是一个相对路径, GCC 可执行程序的路径是 /usr/bin ,那么它在实际工作时指定头文 ...