MyBatis学习总结_11_MyBatis动态Sql语句
MyBatis中对数据库的操作,有时要带一些条件,因此动态SQL语句非常有必要,下面就主要来讲讲几个常用的动态SQL语句的语法
MyBatis中用于实现动态SQL的元素主要有:
- if
- choose(when,otherwise)
- trim
- where
- set
- foreach
1、if
对属性进行判断,如果不为空则执行判断条件
- <select id="selectByCriteria" parameterType="com.mucfc.dto.Student" resultMap="BaseResultMap">
- select * from t_student
- where
- <if test="stuId != null and stuId !=''">
- STU_ID = #{stuId}
- </if>
- <if test="stuName != null and stuName !=''" >
- and STU_NAME = #{stuName}
- </if>
- <if test="stuClass != null and stuClass !=''">
- and STU_CLASS = #{stuClass}
- </if>
- <if test="stuSex != null and stuSex !=''">
- and STU_SEX=#{stuSex}
- </if>
- <if test="stuAge != null and stuAge !=''">
- and STU_AGE=#{stuAge}
- </if>
- </select>
来看看结果:
这是从web页面输入的参数
这是输出的结果
这是打印出来的Sql语句
从结果可以看出,只有在条件不为空的时候,属性才会赋值。
2、where
当where中的条件使用的if标签较多时,这样的组合可能会导致错误。我们以在1中的查询语句为例子,当输入参数stuId为空时,就会报错
然后是输出的结果:
此时SQL语句变成了select * from t_student where and STU_SEX=?这样会报错
如果上面例子,参数stuId为null,将不会进行STUDENT_NAME列的判断,则会直接导“WHERE AND”关键字多余的错误SQL。这时我们可以使用where动态语句来解决。这个“where”标签会知道如果它包含的标签中有返回值的话,它就插入一个‘where’。此外,如果标签返回的内容是以AND 或OR 开头的,则它会剔除掉。
可以改成如下:
- <select id="selectByCriteria" parameterType="com.mucfc.dto.Student" resultMap="BaseResultMap">
- select * from t_student
- <where>
- <if test="stuId != null and stuId !=''">
- STU_ID = #{stuId}
- </if>
- <if test="stuName != null and stuName !=''" >
- and STU_NAME = #{stuName}
- </if>
- <if test="stuClass != null and stuClass !=''">
- and STU_CLASS = #{stuClass}
- </if>
- <if test="stuSex != null and stuSex !=''">
- and STU_SEX=#{stuSex}
- </if>
- <if test="stuAge != null and stuAge !=''">
- and STU_AGE=#{stuAge}
- </if>
- </where>
- </select>
再来看看,输入查询条件
然后输出结果
打印出来的SQL语句
- ==> Preparing: select * from t_student WHERE STU_SEX=?
==> Parameters: 男(String)
<== Total: 14
说明结果是正确的。如果它包含的标签中有返回值的话就插入一个where。此外如果标签返回的内容是以AND或OR开头的,则它会剔除掉。
3、set
当update语句中没有使用if标签时,如果有一个参数为null,都会导致错误。
当在update语句中使用if标签时,如果前面的if没有执行,则或导致逗号多余错误。使用set标签可以将动态的配置SET 关键字,和剔除追加到条件末尾的任何不相关的逗号。
使用if+set标签修改后,如果某项为null则不进行更新,而是保持数据库原值。如下示例:
4、trim
trim是更灵活的去处多余关键字的标签,他可以实践where和set的效果。
- <select id="selectByCriteria" parameterType="com.mucfc.dto.Student" resultMap="BaseResultMap">
- select * from t_student
- <trim prefix="where" prefixOverrides="AND|OR">
- <if test="stuId != null and stuId !=''">
- STU_ID = #{stuId}
- </if>
- <if test="stuName != null and stuName !=''" >
- and STU_NAME = #{stuName}
- </if>
- <if test="stuClass != null and stuClass !=''">
- and STU_CLASS = #{stuClass}
- </if>
- <if test="stuSex != null and stuSex !=''">
- and STU_SEX=#{stuSex}
- </if>
- <if test="stuAge != null and stuAge !=''">
- and STU_AGE=#{stuAge}
- </if>
- </trim>
- </select>
首先判断是否需要where,如果需要,它会自动判断如果where后面有and或者or,就自动把它们都去掉。prefix是前置的,还有suffix是后置的。
如下输入查找参数stuclass=2。
看看打印出来的语句
suffix是后置的例子
- <insert id="insert" parameterType="com.mucfc.dto.Student" >
- insert into t_student
- <trim prefix="(" suffix=")" suffixOverrides="," >
- <if test="stuId != null" >
- STU_ID,
- </if>
- <if test="stu_name!= null" >
- STU_NAME,
- </if>
- </trim>
- <trim prefix="values (" suffix=")" suffixOverrides="," >
- <if test="stuId != null" >
- #{stuId},
- </if>
- <if test="stu_name != null" >
- #{stu_name},
- </if>
- <pre name="code" class="html"> </insert</pre><br>
这里是自动判断是否为空,然后去掉逗号
- prefix="(" suffix=")"
会自动判断是否需要加上()这个符号
5、choose
有时候我们并不想应用所有的条件,而只是想从多个选项中选择一个。而使用if标签时,只要test中的表达式为true,就会执行if标签中的条件。MyBatis提供了choose 元素。if标签是与(and)的关系,而choose比傲天是或(or)的关系。
choose标签是按顺序判断其内部when标签中的test条件出否成立,如果有一个成立,则choose结束。当choose中所有when的条件都不满则时,则执行otherwise中的sql。类似于Java 的switch 语句,choose为switch,when为case,otherwise则为default。
- <!-- 满足其中一个条件时候用choose when操作 -->
- <select id="selectByCriteria" parameterType="com.mucfc.dto.Student" resultMap="BaseResultMap">
- select * from t_student
- <where>
- <choose>
- <when test="stuId != null and stuId !=''">
- STU_ID = #{stuId}
- </when>
- <when test="stuClass != null and stuClass !=''">
- and STU_CLASS = #{stuClass}
- </when>
- <otherwise>
- </otherwise>
- </choose>
- </where>
- </select>
输入两个参数
这里会跳过王五这个参数,因为stuId不为空
然后看打印了来的语句,果然只有一个条件,所以说明是对的
foreach
对于动态SQL 非常必须的,主是要迭代一个集合,通常是用于IN 条件。List 实例将使用“list”做为键,数组实例以“array” 做为键。
foreach元素是非常强大的,它允许你指定一个集合,声明集合项和索引变量,它们可以用在元素体内。它也允许你指定开放和关闭的字符串,在迭代之间放置分隔符。这个元素是很智能的,它不会偶然地附加多余的分隔符。
注意:你可以传递一个List实例或者数组作为参数对象传给MyBatis。当你这么做的时候,MyBatis会自动将它包装在一个Map中,用名称在作为键。List实例将会以“list”作为键,而数组实例将会以“array”作为键。
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
下面分别来看看上述三种情况的示例代码:
1.单参数List的类型:
- <select id="dynamicForeachTest" resultType="Blog">
- select * from t_blog where id in
- <foreach collection="list" index="index" item="item" open="(" separator="," close=")">
- #{item}
- </foreach>
- </select>
上述collection的值为list,对应的Mapper是这样的
- public List<Blog> dynamicForeachTest(List<Integer> ids);
测试代码:
- @Test
- public void dynamicForeachTest() {
- SqlSession session = Util.getSqlSessionFactory().openSession();
- BlogMapper blogMapper = session.getMapper(BlogMapper.class);
- List<Integer> ids = new ArrayList<Integer>();
- ids.add(1);
- ids.add(3);
- ids.add(6);
- List<Blog> blogs = blogMapper.dynamicForeachTest(ids);
- for (Blog blog : blogs)
- System.out.println(blog);
- session.close();
- }
2.单参数array数组的类型:
- <select id="dynamicForeach2Test" resultType="Blog">
- select * from t_blog where id in
- <foreach collection="array" index="index" item="item" open="(" separator="," close=")">
- #{item}
- </foreach>
- </select>
上述collection为array,对应的Mapper代码:
- public List<Blog> dynamicForeach2Test(int[] ids);
对应的测试代码:
- @Test
- public void dynamicForeach2Test() {
- SqlSession session = Util.getSqlSessionFactory().openSession();
- BlogMapper blogMapper = session.getMapper(BlogMapper.class);
- int[] ids = new int[] {1,3,6,9};
- List<Blog> blogs = blogMapper.dynamicForeach2Test(ids);
- for (Blog blog : blogs)
- System.out.println(blog);
- session.close();
- }
3.自己把参数封装成Map的类型
- <select id="dynamicForeach3Test" resultType="Blog">
- select * from t_blog where title like "%"#{title}"%" and id in
- <foreach collection="ids" index="index" item="item" open="(" separator="," close=")">
- #{item}
- </foreach>
- </select>
上述collection的值为ids,是传入的参数Map的key,对应的Mapper代码:
- public List<Blog> dynamicForeach3Test(Map<String, Object> params);
对应测试代码:
- @Test
- public void dynamicForeach3Test() {
- SqlSession session = Util.getSqlSessionFactory().openSession();
- BlogMapper blogMapper = session.getMapper(BlogMapper.class);
- final List<Integer> ids = new ArrayList<Integer>();
- ids.add(1);
- ids.add(2);
- ids.add(3);
- ids.add(6);
- ids.add(7);
- ids.add(9);
- Map<String, Object> params = new HashMap<String, Object>();
- params.put("ids", ids);
- params.put("title", "中国");
- List<Blog> blogs = blogMapper.dynamicForeach3Test(params);
- for (Blog blog : blogs)
- System.out.println(blog);
- session.close();
- }
6、联合实例:
- <insert id="batchInsertTrxBillDetailInfo" parameterType="java.util.Map" >
- INSERT ALL
- <foreach collection="list" item="item">
- into TRX_BILL_DETAIL_INFO
- <trim prefix="(" suffix=")" suffixOverrides="," >
- <if test="item.id != null" >
- ID,
- </if>
- <if test="item.custNo != null" >
- CUST_NO,
- </if>
- <if test="item.transCode != null" >
- TRANS_CODE,
- </if>
- <if test="item.transRefno != null" >
- TRANS_REFNO,
- </if>
- <if test="item.transSeqno != null" >
- TRANS_SEQNO,
- </if>
- <if test="item.orderNo != null" >
- ORDER_NO,
- </if>
- <if test="item.transAmt != null" >
- TRANS_AMT,
- </if>
- <if test="item.billDate != null" >
- BILL_DATE,
- </if>
- <if test="item.billFlag != null" >
- BILL_FLAG,
- </if>
- <if test="item.transDesc != null" >
- TRANS_DESC,
- </if>
- </trim>
- <trim prefix="values (" suffix=")" suffixOverrides="," >
- <if test="item.id != null" >
- #{item.id,jdbcType=DECIMAL},
- </if>
- <if test="item.custNo != null" >
- #{item.custNo,jdbcType=CHAR},
- </if>
- <if test="item.transCode != null" >
- #{item.transCode,jdbcType=CHAR},
- </if>
- <if test="item.transRefno != null" >
- #{item.transRefno,jdbcType=CHAR},
- </if>
- <if test="item.transSeqno != null" >
- #{item.transSeqno,jdbcType=VARCHAR},
- </if>
- <if test="orderNo != null" >
- #{item.orderNo,jdbcType=CHAR},
- </if>
- <if test="item.transAmt != null" >
- #{item.transAmt,jdbcType=DECIMAL},
- </if>
- <if test="item.billDate != null" >
- #{item.billDate,jdbcType=DECIMAL},
- </if>
- <if test="item.billFlag != null" >
- #{item.billFlag,jdbcType=CHAR},
- </if>
- <if test="item.transDesc != null" >
- #{item.transDesc,jdbcType=VARCHAR},
- </if>
- </trim>
- </foreach>
- select 1 from dual
- </insert>
MyBatis学习总结_11_MyBatis动态Sql语句的更多相关文章
- MyBatis学习 之 二、SQL语句映射文件(2)增删改查、参数、缓存
目录(?)[-] 二SQL语句映射文件2增删改查参数缓存 select insert updatedelete sql parameters 基本类型参数 Java实体类型参数 Map参数 多参数的实 ...
- MyBatis学习 之 二、SQL语句映射文件(1)resultMap
目录(?)[-] 二SQL语句映射文件1resultMap resultMap idresult constructor association联合 使用select实现联合 使用resultMap实 ...
- MyBatis:学习笔记(4)——动态SQL
MyBatis:学习笔记(4)——动态SQL
- MyBatis学习06(动态SQL和缓存)
10.动态SQL 10.1 什么是动态SQL 动态SQL指的是根据不同的查询条件 , 生成不同的Sql语句. 官网描述: MyBatis 的强大特性之一便是它的动态 SQL.如果你有使用 JDBC 或 ...
- MyBatis 源码分析——动态SQL语句
有几年开发经验的程序员应该都有暗骂过原生的SQL语句吧.因为他们不能一句就搞定一个业务,往往还要通过代码来拼接相关的SQL语句.相信大家会理解SQL里面的永真(1=1),永假(1=2)的意义吧.所以m ...
- Mybatis学习笔记之---动态sql中标签的使用
动态Sql语句中标签的使用 (一)常用标签 1.<if> if标签通常用于WHERE语句中,通过判断参数值来决定是否使用某个查询条件, 他也经常用于UPDATE语句中判断是否更新某一个字段 ...
- Mybatis(三)动态sql语句
动态sql语句操作 1.MyBatis中#{ }和${ }的区别 在 mapper 中定义的参数传到 xml 中之后,在查询之前 mybatis 会对其进行动态解析.mybatis 为我们提供了两种支 ...
- mybatis学习记录五——动态sql
8 动态sql 8.1 什么是动态sql mybatis核心 对sql语句进行灵活操作,通过表达式进行判断,对sql进行灵活拼接.组装. 8.2 需求 用户信息综合查询列表 ...
- 1.3(Mybatis学习笔记)动态SQL
一.<if> 使用<if>可以根据具体情况来拼接SQL语句,使其更加灵活更加适应我们的需求. <if>的标签体中是需要拼接的语句,满足条件才会将其进行拼接. < ...
随机推荐
- SqlServer正在执行的sql语句
SELECT [Spid] = session_Id ,ecid ,[Database] = DB_NAME(sp.dbid) ,[User] = nt_username ,[Status] = er ...
- 团队开发——SCRUM报告(一)
一.成员介绍 队长:胡亚宝 PM:曹美娜 成员:焦燕.袁亚姣.黄亚萍 二.sprint会议 由于之前是一五一小长假,所以距离上次会议中间隔了很长时间,这里在对上次会议做一下简单的汇总 在上次会议上我们 ...
- Mac系统如何配置adb
在使用mac进行android开发之前,我们一般会安装android studio 或者 eclipse,无论哪一款开发软件,都少不了安装adb(Android Debug Bridge).adb(A ...
- NYOJ-21 三个水杯 AC 分类: NYOJ 2014-02-08 11:35 174人阅读 评论(0) 收藏
人生中第一个AC的广搜题目,喵呜,C++的STL果真不错, #include<stdio.h> #include<queue> #include<string.h> ...
- secure CRT记住密码不可用
secure CRT 记住密码,琢磨好几天了. 终于发现要在软件打开的时候设置了密码才能让每个会话记住密码. 一直懒得在打开软件的时候设置密码,结果每次打开会话都要输入密码...为了省下输入一次密码, ...
- JAVA数据结构系列 栈
java数据结构系列之栈 手写栈 1.利用链表做出栈,因为栈的特殊,插入删除操作都是在栈顶进行,链表不用担心栈的长度,所以链表再合适不过了,非常好用,不过它在插入和删除元素的时候,速度比数组栈慢,因为 ...
- Asp.net的服务器推技术 (Server Push)
在以往的和服务器端通信技术中,我们多数使用的是AJAX轮询式访问,也就是在Javascript中控制时间间隔,然后每隔一段时间就访问一次服务器,然后获得数据或通知.但是这种轮询方式的访问有90%是在做 ...
- HDOJ 1050 Moving Tables
Moving Tables Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 65536/32768 K (Java/Others)Tot ...
- Cortex-M3/4的Hard Fault调试方法
1 Cortex-M3/4的Fault简介 Cortex-M3/4的Fault异常是由于非法的存储器访问(比如访问0地址.写只读存储位置等)和非法的程序行为(比如除以0等)等造成的.常见的4种异常及产 ...
- 理解ASP.NET MVC Framework Action Filters
原文:http://www.cnblogs.com/darkdawn/archive/2009/03/13/1410477.html 本指南主要解释action filters,action filt ...