在我们传统的开发中我们会通过拼接sql达到数据库的操作。java中的拼接不仅效率低下而且代码很长不易维护。而Mybatis通过代理模式实现SQL语句的组装。简洁易懂。

常用标签

元素 作用 备注
if 判断语句 条件分支
choose switch 多条件分支
trim 去除空字符 特殊处理
foreach 集合循环 遍历

if元素

  • if元素是常用的语句,常常在where内部和test结合使用。
  • 在大部分if使用简单。比如我们在查询的时候就可以动态添加name字段。

<select id="selectUser">
select id,name,user_sex from User
<where>
<if test="name!=null and name!=''">
and name like concat('%',concat(#{name},'%'))
</if>
</where>
</select>
  • 上面的sql实现的效果就是如果方法中传递了name参数则以name为条件查询数据。如果没有传递name 则是全表查询数据

choose元素

  • choose类似于java中的switch。类似的标签还有when 、 otherwise元素

<select id="selectUser"> select id , name , user_sex from User
<where>
<choose>
<when test="name!=null and name!=''">
and name like concat('%',concat(#{name},'%'))
</when>
<when test="id!=null and id!=''">
and id=#{id}
</when>
<otherwise>
and user_sex=#{userSex}
</otherwise>
</choose>
</where> </select>

trim元素

  • 上面我们已经使用了一个特殊标签 where . 这个标签加上就是产生条件语句的。如果没有条件语句name这个where 就没有。
  • 关于trim 标签也可以实现类似where的作用。

<select id="selectUser">
select id , name , user_sex from User
<trim prefix="where" prefixOverrides="and">
<if test="name!=null and name!=''">
and name like concat('%',concat(#{name},'%'))
</if>
</trim>
</select>
  • trim元素就意味着我们需要去掉一些特殊字符串。prefix代表的语句的前缀。而prefexOverrides代表的是你需要去掉的字符串。上面的写法基本与where是等效的。update中使用set也是和trim是等效的。

forearch

  • forearch元素就是一个集合遍历。在我们开发中也是常用的一种数据

<select id="selectUser"> select * from User where user_sex in
<forearch item="sex" index="index" collection="sexList" open="(" close="}" separator=",">
#{sex}
</forearch> </select>
  • collection 配置的sexList是传递过来的集合
  • item配置的是循环中当前元素
  • index 配置的当前元素在集合中下标
  • open 和 close 配置的是已什么符号将这些元素包装起来
  • separator 是各个元素的间隔符

bind元素

  • bind元素的作用是通过OGNL表达式自定义一个上下文变量。这样更方便我们使用。在我们进行模糊查询的时候,如果是Mysql数据库,我们常常用到的是一个concat用"%"和参数连接。然而Oracle数据库则是用连接符号"||",这样SQL就需要提供两种形式实现。但是有了bind元素,我们就完全不必使用数据库语言。只需要使用Mybaits语法了。

<select id="selectUser"> <bind name="pattern" value="'%'+_parameter+'%'"/>
select id , name , user_sex from User
where name like #{pattern}
</select>
  • 上面的_parameter代表的就是传递进来的参数,他和通配符连接后,赋给了pattern。我们就可以在select语句中使用这个变量进行模糊查询了。不管是Mysql还是Oracle数据库都可以使用这样进行查询。

最新文章

  1. Maven常用插件
  2. oracle 9i相关问题
  3. Java 分页通用
  4. 在ASP.NET 5中使用SignalR
  5. 如何更新Android SDK和Build Tool
  6. 实现iOS项目一款用swift实现的应用top源码
  7. 用endsWith()来限制图片的后缀名
  8. MVC 界面开发
  9. java Http消息传递之POST和GET两种方法--通过实用工具类来获取服务器资源
  10. php图片上传服务器
  11. ELK日志检索并邮件微信通知
  12. TomCat的安装及测试
  13. [2017BUAA软工助教]团队alpha得分总表
  14. python2.x 到 python3.x 中“url”部分变化
  15. phpcs
  16. tomcat允许跨域请求:
  17. [LeetCode&amp;Python] Problem 896. Monotonic Array
  18. express总结(一)
  19. 内置锁(一)synchronized 介绍与用法
  20. [Luogu 3128] USACO15DEC Max Flow

热门文章

  1. Linux 通过终端命令行切换系统语言
  2. 单片机P0口
  3. [hdu1402]大数乘法(FFT模板)
  4. 瞬间教你学会使用java中list的retainAll方法
  5. 【clear linux】intel clear linux 电源状态命令
  6. 使用ultraISO制作U盘制作系统盘提醒:设备忙,请退出所有在运行的应用。
  7. Linux之cat的使用介绍
  8. 数据库范式1NF 2NF 3NF详细阐述
  9. 如何使用Postman生成不同格式测试的报告
  10. Django之钩子Hook方法