Mybatis之动态SQL

mybatis 的动态sql语句是基于OGNL表达式的。可以方便的在 sql 语句中实现某些逻辑. 总体说来mybatis 动态SQL 语句主要有以下几类:

  • if
  • choose (when, otherwise)
  • trim (where, set)
  • foreach

if

动态 SQL 通常要做的事情是有条件地包含 where 子句的一部分。

   <select id="selectUserByOrgid"  resultType="java.util.HashMap">
select username,password from sys_user where org_id = #{orgid,jdbcType=VARCHAR}
<if test="orderFiled != null" >
order by ${orderFiled}
<if test="orderSort != null" >
${orderSort}
</if>
</if>
</select>

choose, when, otherwise

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

  <select id="selectByUsernameORorg" parameterType="java.lang.String" resultMap="BaseResultExtMap">
select
<include refid="Base_Ext_Column_List" />
from sys_user
where
<choose>
<when test="username != null">
AND username like#{username,jdbcType=VARCHAR}
</when>
<when test="name != null ">
AND name like #{name,jdbcType=VARCHAR}
</when>
<otherwise>
AND org_id =#{orgid,jdbcType=VARCHAR}
</otherwise>
</choose>
</select>

trim, where, set

前面几个例子已经合宜地解决了一个臭名昭著的动态 SQL 问题。为了解决前面SQL可能出现的问题,就是使用where标签改写。where标签非常智能。如果标签内部没有合适的语句,where标签就不会生成任何东西,防止出现错误语句。

 <select id="selectByUsernameORorg2" parameterType="java.lang.String" resultMap="BaseResultExtMap">
select
<include refid="Base_Ext_Column_List" />
from sys_user
<where>
<if test="name != null">
name = #{name,jdbcType=VARCHAR}
</if>
<if test="username != null">
AND username like #{username,jdbcType=VARCHAR}
</if>
</where>
</select>

有时候where标签还不能满足需求。这时候还可以使用trim标签进行更高级的定制。trim标签中的prefix和suffix属性会被用于生成实际的SQL语句,会和标签内部的语句拼接。如果语句的前面或后面遇到prefixOverrides或suffixOverrides属性中指定的值,MyBatis会自动将它们删除。在指定多个值的时候,别忘了每个值后面都要有一个空格,保证不会和后面的SQL连接在一起。下面这个例子和where标签完全等效。

 <trim prefix="WHERE" prefixOverrides="AND |OR ">
...
</trim>

类似的用于动态更新语句的解决方案叫做 set。set 元素可以被用于动态包含需要更新的列,而舍去其他的。

 <update id="updateByPrimaryKeySelective" parameterType="com.goku.mybatis.model.sysUser">
<!--
WARNING - @mbg.generated
This element is automatically generated by MyBatis Generator, do not modify.
-->
update sys_user
<set>
<if test="username != null">
username = #{username,jdbcType=VARCHAR},
</if>
<if test="password != null">
password = #{password,jdbcType=VARCHAR},
</if>
<if test="name != null">
name = #{name,jdbcType=VARCHAR},
</if>
<if test="sex != null">
sex = #{sex,jdbcType=VARCHAR},
</if>
<if test="status != null">
status = #{status,jdbcType=CHAR},
</if>
<if test="orgId != null">
org_id = #{orgId,jdbcType=VARCHAR},
</if>
<if test="email != null">
email = #{email,jdbcType=VARCHAR},
</if>
<if test="idcard != null">
idcard = #{idcard,jdbcType=VARCHAR},
</if>
<if test="isAdmin != null">
is_admin = #{isAdmin,jdbcType=VARCHAR},
</if>
<if test="sort != null">
sort = #{sort,jdbcType=BIGINT},
</if>
<if test="mobile != null">
mobile = #{mobile,jdbcType=VARCHAR},
</if>
<if test="stationid != null">
stationid = #{stationid,jdbcType=LONGVARCHAR},
</if>
</set>
where id = #{id,jdbcType=VARCHAR}
</update>

这里,set 元素会动态前置 SET 关键字,同时也会消除无关的逗号,因为用了条件语句之后很可能就会在生成的赋值语句的后面留下这些逗号。

若你对等价的自定义 trim 元素的样子感兴趣,那这就应该是它的真面目:

 <trim prefix="SET" suffixOverrides=",">
...
</trim>

foreach

动态 SQL 的另外一个常用的必要操作是需要对一个集合进行遍历,通常是在构建 IN 条件语句的时候

  <select id="selectUserByOrgid2"  resultType="java.util.HashMap">
select username,password from sys_user where org_id IN
<foreach item="item" index="index" collection="list"
open="(" separator="," close=")">
#{item}
</foreach>
</select>

bind

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

  <select id="selectByUsername2" parameterType="java.lang.String" resultMap="BaseResultExtMap">
<bind name="username" value="'%' + username + '%'" />
select
<include refid="Base_Ext_Column_List" />
from sys_user
where username LIKE #{username}
</select>

GITHUB

github :  https://github.com/nbfujx/learn-java-demo/tree/master/Goku.MybatisDemo.XML

Mybatis基于XML配置SQL映射器(三)的更多相关文章

  1. Mybatis基于XML配置SQL映射器(二)

    Mybatis之XML注解 之前已经讲到通过 mybatis-generator 生成mapper映射接口和相关的映射配置文件: 下面我们将详细的讲解具体内容 首先我们新建映射接口文档  sysUse ...

  2. Mybatis基于XML配置SQL映射器(一)

    Durid和Mybatis开发环境搭建 SpringBoot搭建基于Spring+SpringMvc+Mybatis的REST服务(http://www.cnblogs.com/nbfujx/p/76 ...

  3. mybatis 基于xml 配置的映射器

    cache  给命名空间的缓存配置 cache-ref 其他命名空间缓存配置的引用 resultMap 描述如何从数据库结果集中来加载对象 <!--column不做限制,可以为任意表的字段,而p ...

  4. Java Persistence with MyBatis 3(中文版) 第三章 使用XML配置SQL映射器

    关系型数据库和SQL是经受时间考验和验证的数据存储机制.和其他的ORM 框架如Hibernate不同,MyBatis鼓励开发者可以直接使用数据库,而不是将其对开发者隐藏,因为这样可以充分发挥数据库服务 ...

  5. MyBatis学习笔记3--使用XML配置SQL映射器

    <resultMap type="Student" id="StudentResult"> <id property="id&quo ...

  6. 小峰mybatis(5)mybatis使用注解配置sql映射器--动态sql

    一.使用注解配置映射器 动态sql: 用的并不是很多,了解下: Student.java 实体bean: package com.cy.model; public class Student{ pri ...

  7. (三)使用XML配置SQL映射器

    SqlSessionFactoryUtil.java package com.javaxk.util; import java.io.IOException; import java.io.Input ...

  8. 小峰mybatis(4)mybatis使用注解配置sql映射器

    主流开发还是使用xml来配置:使用注解配置比较快,但是不支持所有功能:有些功能还是得用配置文件: 一.基本映射语句: @Inert @Update @Delete @Select 二.结果集映射语句 ...

  9. MyBatis 3 使用注解配置SQL映射器

    l 在映射器Mapper接口上使用注解 l 映射语句 @Insert,@Update,@Delete,@SeelctStatements l 结果映射 一对一映射 一对多映射 l 动态SQL @Sel ...

随机推荐

  1. LeetCode算法题

    1.给两个整数数组 A 和 B ,返回两个数组中公共的.长度最长的子数组的长度. 时间复杂度待优化 class Solution { public int findLength(int[] A, in ...

  2. nil,Nil,NULL和NSNull的区别

  3. JS中arguments对象

    与其他程序设计语言不同,ECMAScript 不会验证传递给函数的参数个数是否等于函数定义的参数个数. 开发者定义的函数都可以接受任意个数的参数而无需跟定义的函数相匹配(根据 Netscape 的文档 ...

  4. socket | tcp客户端 tcp服务器 udp客户端 udp 服务器 创建方法

    tcp服务器 #coding=utf-8 ''' 这里是tcp服务器端,要先启动 ''' import socket import threading bind_ip = "0.0.0.0& ...

  5. 用 Flask 来写个轻博客 (29) — 使用 Flask-Admin 实现后台管理 SQLAlchemy

    目录 目录 前文列表 扩展阅读 Flask-Admin BaseView 基础管理页面 ModelView 实现效果 前文列表 用 Flask 来写个轻博客 (1) - 创建项目 用 Flask 来写 ...

  6. Gson字符串转换对象数组

    public class Input { private String title; private int formId; private String content; public String ...

  7. CentOS7下Docker与.net Core 2.2

    一.使用 yum 安装(CentOS 7下) Docker 要求 CentOS 系统的内核版本高于 3.10 ,查看本页面的前提条件来验证你的CentOS 版本是否支持 Docker . 通过 una ...

  8. bstToDoublyList

    bstToDoublyList */--> code {color: #FF0000} pre.src {background-color: #002b36; color: #839496;} ...

  9. how to prevent lowmemorykiller from killing processes

    Hi there, I've upgraded a number of test systems to the latest Saucy beta. I've seen quite a few cas ...

  10. window.location.search 为何在url 带# 号时获取不到 ?

    我们在获取url参数时,会常常用到截取参数 getUrlParam(name) { const reg = new RegExp('(^|&)' + name + '=([^&]*)( ...