动态SQL语句

MyBatis 的强大特性之一便是它的动态 SQL。如果你有使用 JDBC 或其它类似框架的经验,你就能体会到根据不同条件拼接 SQL 语句的痛苦。例如拼接时要确保不能忘记添加必要的空格,还要注意去掉列表最后一个列名的逗号。利用动态 SQL 这一特性可以彻底摆脱这种痛苦。

虽然在以前使用动态 SQL 并非一件易事,但正是 MyBatis 提供了可以被用在任意 SQL 映射语句中的强大的动态 SQL 语言得以改进这种情形。

动态 SQL 元素和 JSTL 或基于类似 XML 的文本处理器相似。在 MyBatis 之前的版本中,有很多元素需要花时间了解。MyBatis 3 大大精简了元素种类,现在只需学习原来一半的元素便可。MyBatis 采用功能强大的基于 OGNL 的表达式来淘汰其它大部分元素。

if语句

动态 SQL 通常要做的事情是根据条件包含 where 子句的一部分。比如:

<select id="queryUser" resultMap="baseMap"
resultType="com.sxt.bean.User" parameterType="user">
select id ,name ,age from t_user
where 1 =1
<if test="username!=null">
and name = #{username}
</if>
</select>
// 接口
public List<User> queryUser(User user);

测试

choose, when, otherwise

有时我们不想应用到所有的条件语句,而只想从中择其一项。针对这种情况,MyBatis 提供了 choose 元素,它有点像 Java 中的 switch 语句

<select id="findActiveBlogLike"
resultType="Blog">
SELECT * FROM BLOG WHERE state = ‘ACTIVE’
<choose>
<when test="title != null">
AND title like #{title}
</when>
<when test="author != null and author.name != null">
AND author_name like #{author.name}
</when>
<otherwise>
AND featured = 1
</otherwise>
</choose>
</select>

where语句

在使用if语句做动态条件处理的时候如果所有条件都不满足,那么得到的SQL语句如下:

select * from t_user where

在这种情况下,我们一般会加一个1=1来匹配语法规则

	<select id="queryUser" resultMap="baseMap"
resultType="com.sxt.bean.User" parameterType="user">
select id ,name ,age from t_user
where 1 =1
<if test="username!=null">
and name = #{username}
</if>
</select>

此时可以使用标签来处理这种情况

	<select id="queryUser" resultMap="baseMap"
resultType="com.sxt.bean.User" parameterType="user">
select id ,name ,age from t_user
<where>
<if test="username!=null">
and name = #{username}
</if>
</where>
</select>

set语句

set主要也是用来解决更新问题的。

<update id="updateBookById">
update t_book
<set>
<if test="author!=null"> author=#{author},</if>
<if test="name!=null"> b_name=#{name},</if>
<if test="price!=null"> price=#{price},</if>
</set>
where id=#{id};
</update>

trim

trim标记是一个格式化的标记,可以完成set或者是where标记的功能

属性 说明
prefix 前缀
prefixOverrides 去掉第一个指定内容
suffix 后缀
suffixoverride 去掉最后一个指定内容

替代<where>的用法

	<select id="queryUser" resultMap="baseMap" resultType="com.sxt.bean.User"
parameterType="user">
select id ,name ,age from t_user
<!-- <where>
<if test="username!=null">
and name = #{username}
</if>
</where> -->
<trim prefix="where" prefixOverrides="AND |OR ">
<if test="username!=null">
and name = #{username}
</if>
<if test="age != 0">
and age = #{age}
</if>
</trim>
</select>

替代<set>的用法

<update id="updateUser" parameterType="User">
update t_user
<trim prefix="set" suffixOverrides=",">
<if test="username!=null">
name = #{username},
</if>
<if test="age != 0">
age = #{age}
</if>
</trim>
where id=#{id}
</update>

或者

<update id="updateUser" parameterType="User">
update t_user
set
<trim suffixOverrides=",">
<if test="username!=null">
name = #{username},
</if>
<if test="age != 0">
age = #{age}
</if>
</trim>
where id=#{id}
</update>

foreach语句

foreach用来遍历,遍历的对象可以是数组,也可以是集合。

属性 说明
collection collection属性的值有三个分别是list、array、map三种
open 前缀
close 后缀
separator 分隔符,表示迭代时每个元素之间以什么分隔
item 表示在迭代过程中每一个元素的别名
index 用一个变量名表示当前循环的索引位置

接口中方法

public interface UserMapper {
// 如果不指定@Param 默认是array
public List<User> queryUserByIds(@Param("ids")List<Integer> ids); public int insertUser(@Param("users")List<User> users);
}
<select id="queryUserByIds" resultType="user">
select * from t_user where id in
<foreach collection="ids" open="(" close=")" separator="," item="id" >
#{id}
</foreach>
</select> <insert id="insertUser">
insert into t_user(name,age)values
<foreach collection="users" item="user" separator=",">
(#{user.name},#{user.age})
</foreach>
</insert>

bind

bind 元素可以从 OGNL 表达式中创建一个变量并将其绑定到上下文。

<select id="getUserById" resultMap="baseMap" resultType="com.sxt.bean.User">
<!-- 声明了一个参数aaa 在后面就可以使用了 -->
<bind name="aaa" value="12"/>
select
id ,name ,age from t_user where id=${aaa}
</select>

sql块

sql片段一般用来定义sql中的列

mybatis教程4(动态SQL)的更多相关文章

  1. 11、MyBatis教程之动态SQL

    12.动态SQL 1.介绍 什么是动态SQL:动态SQL指的是根据不同的查询条件 , 生成不同的Sql语句. 官网描述: MyBatis 的强大特性之一便是它的动态 SQL.如果你有使用 JDBC 或 ...

  2. SpringBoot使用Mybatis注解开发教程-分页-动态sql

    代码示例可以参考个人GitHub项目kingboy-springboot-data 一.环境配置 1.引入mybatis依赖 compile( //SpringMVC 'org.springframe ...

  3. 【mybatis深度历险系列】mybatis中的动态sql

    最近一直做项目,博文很长时间没有更新了,今天抽空,学习了一下mybatis,并且总结一下.在前面的博文中,小编主要简单的介绍了mybatis中的输入和输出映射,并且通过demo简单的介绍了输入映射和输 ...

  4. Mybatis入门之动态sql

    Mybatis入门之动态sql 通过mybatis提供的各种标签方法实现动态拼接sql. 1.if.where.sql.include标签(条件.sql片段) <sql id="sel ...

  5. mybatis 详解------动态SQL

    mybatis 详解------动态SQL   目录 1.动态SQL:if 语句 2.动态SQL:if+where 语句 3.动态SQL:if+set 语句 4.动态SQL:choose(when,o ...

  6. mybatis中的动态SQL

    在实际开发中,数据库的查询很难一蹴而就,我们往往要根据各种不同的场景拼接出不同的SQL语句,这无疑是一项复杂的工作,我们在使用mybatis时,mybatis给我们提供了动态SQL,可以让我们根据具体 ...

  7. Mybatis映射文件动态SQL语句-01

    因为在很多业务逻辑复杂的项目中,往往不是简单的sql语句就能查询出来自己想要的数据,所有mybatis引入了动态sql语句, UserMapper.xml <?xml version=" ...

  8. 6.Mybatis中的动态Sql和Sql片段(Mybatis的一个核心)

    动态Sql是Mybatis的核心,就是对我们的sql语句进行灵活的操作,他可以通过表达式,对sql语句进行判断,然后对其进行灵活的拼接和组装.可以简单的说成Mybatis中可以动态去的判断需不需要某些 ...

  9. MyBatis注解配置动态SQL

    MySQL创建表 DROP TABLE IF EXISTS `tb_employee`; CREATE TABLE `tb_employee` ( `id` int(11) NOT NULL AUTO ...

随机推荐

  1. centos 安装tmux

    安装tmux之前需要先安装一些支持的组件: yum install libevent-devel ncurses-devel 接下来就是下载源码包进行安装了,以1.6版本举例 wget http:// ...

  2. DOM追加笔记

    根据 W3C 的 HTML DOM 标准,HTML 文档中的所有内容都是节点: 整个文档是一个文档节点 每个 HTML 元素是元素节点 HTML 元素内的文本是文本节点 每个 HTML 属性是属性节点 ...

  3. ABP框架系列之四十九:(Startup-Configuration-启动配置)

    ASP.NET Boilerplate provides an infrastructure and a model to configure it and modules on startup. A ...

  4. python模块:json

    r"""JSON (JavaScript Object Notation) <http://json.org> is a subset of JavaScri ...

  5. s5-6 Linux 标准输出 系统优化 目录结构

    标准输出 重定向符号 #>   1>    标准输出重定向  先把文件的内容清空   把内容放在文件的最后一行 #>>  1>>   追加重定向      把内容放 ...

  6. VDD,VCC,VSS,VEE,VDDA,VSSA,

    VDD是主供电电源,也是IO口输出电平的输入电源.VDDA(A表示模拟)是模拟电源,当使用到模拟信号的时候,比如AD(模数)或者DA(数模)的时候,系统会使用VDDA的电压作为参考电压来.不要求精准使 ...

  7. Go语言正则模块

    基本使用 import "bytes" import "fmt" import "regexp" func main() { //这个测试一 ...

  8. 网页中的数据的4个处理方式:CRUD(Creat, Retrive, Update, Delete)

    网页中的数据的4个处理方式:CRUD(Creat, Retrive, Update, Delete) 2018-12-21, 后续完善

  9. Mysql主从复制读写分离

    一.前言:为什么MySQL要做主从复制(读写分离)?通俗来讲,如果对数据库的读和写都在同一个数据库服务器中操作,业务系统性能会降低.为了提升业务系统性能,优化用户体验,可以通过做主从复制(读写分离)来 ...

  10. 在Ubuntu登陆界面输入密码之后,黑屏一闪后,又跳转到登录界面

    现象:在Ubuntu登陆界面输入密码之后,黑屏一闪后,又跳转到登录界面.原因:主目录下的.Xauthority文件拥有者变成了root,从而以用户登陆的时候无法都取.Xauthority文件.说明:X ...