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 ...
随机推荐
- 消除ADB错误“more than one device and emulator”的方法
当我连着手机充电的时候,启动模拟器调试,运行ADB指令时,报错. C:\Users\gaojs>adb shell error: more than one device and emulato ...
- oc14--匿名对象
// // main.m // 匿名对象 #import <Foundation/Foundation.h> #import "Person.h" #import &q ...
- Floyed理解
Floyed理解 Floyd算法的本质是动态规划,其转移方程为:f(k,i,j) = min( f(k-1,i,j), f(k-1,i,k)+f(k-1,k,j) ). f(k-1,i,j)表示经过前 ...
- hdoj--5621--KK's Point(简单数学)
KK's Point Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 65536/65536 K (Java/Others) Total ...
- Python中断言与异常的区别
异常,在程序运行时出现非正常情况时会被抛出,比如常见的名称错误.键错误等. 异常: >>> s Traceback (most recent call last): File &qu ...
- ASCII和ASCII扩展表
- 【转】PowerDesigner物理数据表生成C#实体类Model
model实体类是什么: 在三层架构UI,BLL,DAL中,有时用户插入一条记录到数据库中,必然会有不少数据,按正常编程,也必然会一下子调用某个函数传入不少参数.为了减少参数的数量,达到高效简洁的效果 ...
- 关于各浏览器下Hack的写法
下面是我收集有关于各浏览器下Hack的写法: 1.Firefox @-moz-document url-prefix() { .selector { property: value; } } 上面是仅 ...
- 给<hr/>添加样式
点线式 破折线式 直线式 双线式 脊线式 槽线式 内嵌效果的 突起效果的 border-top:10px 设置水平线的大小 <hr style=" border-top:5px dot ...
- 应用Struts2框架,开发一个加法器,采用两个页面,一个页面输入数据,另一个界面输出结果。
软件152谭智馗 一.新建maven项目 1.选择菜单file—new—maven project,勾选“Create a &simple project (skip archetype se ...