Mybatis4 之Mybatis动态sql的实现代码


本文整理自网络,侵删。

1.什么是动态SQL

传统的使用JDBC的方法,相信大家在组合复杂的的SQL语句的时候,需要去拼接,稍不注意哪怕少了个空格,都会导致错误。Mybatis的动态SQL功能正是为了解决这种问题, 其通过 if, choose, when, otherwise, trim, where, set, foreach标签,可组合成非常灵活的SQL语句,从而提高开发人员的效率。

SQL语句不固定, 会根据前台用户的操作而进行变化的SQL语句, 可以被称之为动态SQL. 在MyBatis中, 提供了一组标签, 用于方便的实现动态SQL, 不需要通过java代码拼接字符串了.
###2.动态sql中的标签

1. <if>

用于条件判断, test属性表示判断结果, 要求是一个boolean.

2.<where>

用于维护where子句, 通常配合一起使用. 如下功能:
a)当没有条件时, 不会创建WHERE关键字;
b)当有条件时, 会自动生成WHERE关键字;
c)会自动去掉第一个条件的and/or关键字.

3.<choose><when><otherwise>

功能类似于switch…case…default, 表示多分支判断, 只能成立一个条件

<mapper namespace="com.bjsxt.mapper.UserMapper">
 <select id="selByCondition" resultType="user">
 select * from tb_user
 <where>
  <if test="id != null">
  and id=#{id}
  </if>
  <if test="username != null and username != ''">
  and username=#{username}
  </if>
  <if test="age != null">
  and age &lt;&gt; #{age}
  </if>
  <choose>
  <when test="birthday != null and birthday != ''">
   and birthday = #{birthday}
  </when>
  <otherwise>
   and birthday is null
  </otherwise>
  </choose>
 </where>
 </select>
</mapper>

4.<bind>

对参数进行加工, 通常用于模糊查询给参数加通配符

<select id="sel2" resultType="user">
 <include refid="base_sql" />
 <where>
 <if test="realname != null and realname != ''">
  <bind name="realname" value="'%' + realname + '%'"/>
  and realname like #{realname}
 </if>
 </where>
</select>

5.<include>

配合使用, 用于提取通用sql语句片段, 用于引用SQL片段

<sql id="base_sql">
 select
 id, username, password, realname, age, birthday, reg_time regTime
 from tb_user
</sql>
<select id="sel2" resultType="user">
 <include refid="base_sql" />
 <where>
 <if test="realname != null and realname != ''">
  <bind name="realname" value="'%' + realname + '%'"/>
  and realname like #{realname}
 </if>
 </where>
</select>

6.<set>

阅读剩余部分

相关阅读 >>

sql中case when的用法

整理一下sqlserver的排序规则

mysql数据表基本操作实例详解

navicat怎么恢复sql server的数据库备份

oracle使用sql语句增加字段示例(sql删除字段语句)

python orm框架sqlalchemy学习笔记之数据查询实例

19个mysql性能优化要点解析

深入了解mysql逻辑架构

sql好学吗?

sql的临时表使用小结

更多相关阅读请进入《sql》频道 >>


数据库系统概念 第6版
书籍

数据库系统概念 第6版

机械工业出版社

本书主要讲述了数据模型、基于对象的数据库和XML、数据存储和查询、事务管理、体系结构等方面的内容。



打赏

取消

感谢您的支持,我会继续努力的!

扫码支持
扫码打赏,您说多少就多少

打开支付宝扫一扫,即可进行扫码打赏哦

分享从这里开始,精彩与您同在

评论

管理员已关闭评论功能...