动态 SQL 语句大全

读完这篇文章里你能收获到

  1. Mybatis动态SQL语句大全
  2. Mybatis中如何定义变量
  3. Mybatis中如何提取公共的SQL片段

1、if语句

需求:根据作者名字和博客名字来查询博客,如果作者名字为空,那么只根据博客名字查询,反之,则根据作者名来查询

<select id="queryBlogIf" parameterType="map" resultType="blog">select * from blog where<if test="title != null and title != '' ">title = #{title}</if><if test="author != null and author != '' ">and author = #{author}</if>
</select>

这样写我们可以看到,如果 author 等于 null,那么查询语句为 select * from user where title=#{title},但是如果title为空呢?那么查询语句为 select * from user where and author=#{author},这是错误的SQL 语句,如何解决呢?请看下面的 where 语句!

2、where语句

修改上面的SQL语句:

<select id="queryBlogIf" parameterType="map" resultType="blog">select * from blog<where><if test="title != null and title != ''">title = #{title}</if><if test="author != null and author != ''">and author = #{author}</if></where>
</select>

where 元素只会在子元素返回任何内容的情况下才插入 “WHERE” 子句。而且,若子句的开头为 “AND” 或 “OR”,where 元素也会将它们去除

如果 where 元素与你期望的不太一样,你也可以通过自定义 trim 元素来定制 where 元素的功能,如下:

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

prefixOverrides 属性会忽略通过管道分隔的文本序列(注意此例中的空格也是必要的

它的作用是移除所有指定在 prefixOverrides 属性中的内容,并且插入 prefix 属性中指定的内容(注意 prefixOverrides 单词不能写错,包括大小写,否则会报错)

3、set语句

同理,上面的对于查询 SQL 语句包含 where 关键字,如果在进行更新操作的时候,含有 set 关键词,我们怎么处理呢?

<!--注意set是用的逗号隔开-->
<update id="updateBlog" parameterType="map">update blog<set><if test="title != null and title != '' ">title = #{title},</if><if test="author != null and author != '' ">author = #{author}</if></set>where id = #{id}
</update>

这个例子中,set 元素会动态的在行首插入 SET 关键字,并会删掉额外的逗号(这些逗号是在使用条件语句给列赋值时引入的)

也是可以和 trim 搭配使用的,如下:

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

4、choose语句

有时候,我们不想用到所有的查询条件,只想选择其中的一个,查询条件有一个满足即可,使用 choose 标签可以解决此类问题,类似于 Java 的 switch 语句

<select id="queryBlogChoose" parameterType="map" resultType="blog">select * from blog<where><choose><when test="title != null and title != '' ">title = #{title}</when><when test="author != null and author != '' ">and author = #{author}</when><otherwise>and views = #{views}</otherwise></choose></where>
</select>

5、foreach语句

注意:如果需要用SQL进行批量操作的话,数据库连接参数需要设置下面参数:allowMultiQueries=true&rewriteBatchedStatements=true

一般按照下面方式配置即可:

jdbc:mysql://127.0.0.1:3306/test?useUnicode=true&characterEncoding=utf8&allowMultiQueries=true&rewriteBatchedStatements=true&zeroDateTimeBehavior=convertToNull&useSSL=true&serverTimezone=GMT%2B8

1、新增

批量新增博客信息到数据库:

<insert id="batchInsertBlog" useGeneratedKeys="true" keyProperty="id">insert into blog (title, author, views, status) values<foreach collection="blogList" item="blog" separator=",">(#{blog.title}, #{blog.author}, #{blog.views}, #{blog.status})</foreach>
</insert>

mapper中这样写:

int batchInsertBlog(List<Blog> blogList);

2、删除

<delete id="batchDeleteByIds">DELETE FROM blog WHERE id in<foreach collection="ids" item="item" index="index" open="(" separator="," close=")">#{item}</foreach>
</delete>

mapper中这样写:

int batchDeleteByIds(@Param("ids") List<String> ids);

3、更新

对所有表都适用,公用的写法:

<update id="updateTable">UPDATE ${tableName}SET<foreach collection="dataMap" index="key" item="value"  separator="," >${key} = #{value}</foreach>WHEREid = #{id}
</update>

mapper中这样写:

 void updateTable(@Param("tableName") String tableName, Param("id") String id, @Param("dataMap") HashMap dataMap);

4、查询

批量查询博客信息

<select id="getAllBlog"  resultType="blog">SELECT title, author, views, statusFROM blog<if test="blogList != null and blogList.size() > 0">WHERE id in<foreach collection="blogList" item="item" index="index" open="(" separator="," close=")">#{item}</foreach></if>
</select>

mapper中这样写:

 void getAllBlog(@Param("blogList") List<Long> blogList);

6、SQL片段

有时候可能某个 sql 语句我们用的特别多,为了增加代码的重用性,简化代码,我们需要将这些代码抽取出来,然后使用时直接调用。

提取SQL片段:

<sql id="if-title-author"><if test="title != null and title != '' ">title = #{title}</if><if test="author != null and author != '' ">and author = #{author}</if>
</sql>

引用SQL片段:

<select id="queryBlogIf" parameterType="map" resultType="blog">select * from blog<where><!-- 引用 sql 片段,如果refid 指定的不在本文件中,那么需要在前面加上 namespace--><include refid="if-title-author"></include><!-- 在这里还可以引用其他的 sql 片段 --></where>
</select>

注意事项:

  • 最好基于 单表来定义 sql 片段,提高片段的可重用性
  • 在 sql 片段中不要包括 where

7、bind元素

bind 元素允许你在 OGNL 表达式以外创建一个变量,并将其绑定到当前的上下文。比如:

<select id="selectBlogsLike" resultType="Blog"><bind name="pattern" value="'%' + _parameter.getTitle() + '%'" />SELECT * FROM BLOGWHERE title LIKE #{pattern}
</select>

8、总结

相信大家在实际开发中会经常用到上面总结梳理的这些标签元素,确实非常方便,可以大大提高开发效率,希望大家多使用,多练习,熟能生巧

Mybatis动态SQL语句大全相关推荐

  1. 动态 SQL 语句大全

    读完这篇文章里你能收获到 1.Mybatis动态SQL语句大全 2.Mybatis中如何定义变量 3.Mybatis中如何提取公共的SQL片段 1.if语句 需求:根据作者名字和博客名字来查询博客,如 ...

  2. MyBatis——动态SQL语句——if标签和where标签复合使用

    功能需求 根据性别和名字查询用户 官方文档 MyBatis--动态 SQL SQL语句 SELECT id, username, birthday, sex, address FROM `user` ...

  3. Mybatis 动态Sql语句《常用》

    MyBatis 的强大特性之一便是它的动态 SQL.如果你有使用 JDBC 或其他类似框架的经验,你就能体会到根据不同条件拼接 SQL 语句有多么痛苦.拼接的时候要确保不能忘了必要的空格,还要注意省掉 ...

  4. Mybatis—动态SQL语句与逆向工程

    Mybatis动态SQL语句与逆向工程 MyBatis动态SQL语句与逆向工程 1.动态SQL语句 1.1.动态SQL是什么 1.2.动态SQL有什么用 1.3.基于XML的实现 1.3.2.接口文件 ...

  5. MyBatis动态sql语句使用

    一.MyBatis动态语句分为4种元素: 元素 作用 描述 if 条件判断 单条件判断 choose(when.otherwise) 条件选择,相当Java when 多条件分支判断 where.se ...

  6. Mybatis 动态sql语句(if标签和where标签)

    功能:根据性别和名字查询用户 查询sql语句: SELECT id, username, birthday, sex, address FROM `user` WHERE sex = 1 AND us ...

  7. 【转】mybatis实战教程(mybatis in action)之八:mybatis 动态sql语句

    转自:除非申明,文章均为一号门原创,转载请注明本文地址,谢谢! 转载地址:http://blog.csdn.net/kutejava/article/details/9164353#t5 1. if ...

  8. mybatis动态SQL语句

    三.动态SQL语句 有些时候,sql语句where条件中,需要一些安全判断,例如按性别检索,如果传入的参数是空的,此时查询出的结果很可能是空的,也许我们需要参数为空时,是查出全部的信息.这是我们可以使 ...

  9. MyBatis学习总结(11)——MyBatis动态Sql语句

    MyBatis中对数据库的操作,有时要带一些条件,因此动态SQL语句非常有必要,下面就主要来讲讲几个常用的动态SQL语句的语法 MyBatis中用于实现动态SQL的元素主要有: if choose(w ...

最新文章

  1. str python3_python3 str(字符串)
  2. WannaCry勒索软件还在继续传播和感染中
  3. 每日一则----算法----二分查找法
  4. vue中使用lazyload实现图片懒加载
  5. install glm library in ubuntu and use it in qt
  6. MongoDB学习——介绍一款MongoDB连接管理工具
  7. 单独设置一页或者多页的页眉或者页脚
  8. 又一爆款电视剧《沉默的真相》,真的很好看吗?网友的弹幕真相啦
  9. BSC链节点搭建 保姆级详细教程
  10. Java+Springmvc+velement实现高校学科竞赛项目系统+Lw
  11. MySql每晚12点都会弹出这个?
  12. 怎么看台式计算机内存条,内存频率怎么看 教你怎么看内存条频率
  13. Linux配置sendmail实现PHP发送邮件
  14. 对中国标准时间(CST)和中国夏令时(CDT)的不同处理
  15. AFM测试常见问题及解答(二)
  16. 【上海交大oj】畅畅的牙签袋(状态压缩dp)
  17. 360路由器插件_主打游戏加速 360安全路由P4C体验
  18. Pycharm 常用快捷键大全【快查字典版】
  19. 家乐福618安全与性能保卫战(一)-安全高地保卫战
  20. WinXP蓝屏错误stop:c000021a unknown hard error

热门文章

  1. 标点符号在作文中的位置
  2. C#中 如何关联键盘按钮 (KeyChar/KeyCode值 KeyPress/KeyDown事件 区别)
  3. 使用HttpClient实现文件的上传下载
  4. checkbox选中selec才可选和显示隐藏密码
  5. Pandas数据分析初学--开始了解数据
  6. 异步实现:回调回调和消息队列
  7. 一 进程与线程的概念
  8. aac格式怎么转换成mp3?
  9. RubyMine安装gitee插件
  10. 【Sensors】传感器概述(2)