动态SQL

什么是动态SQL?

根据不同的条件生成不同的SQL语句。

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

搭建环境

create table `blog`(
`id` varchar(50) not null comment '博客id',
`title` varchar(100) not null comment '博客标题',
`auther` varchar(30) not null comment '博客作者',
`create_time` datetime not null comment '创建时间',
`views` int(30) not null comment '浏览量'
)engine =innodb default charset =utf8

创建一个基础工程

  1. 导包

  2. 编写配置文件

  3. 编写实体类

    @Data
    public class Blog {
    private int id;
    private String title;
    private String author;
    private Date date;
    private int views;
    }
  4. 编写对应的Mapper接口和MapperXML文件

IF

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

choose(where,otherwise)

<choose>
<when test="title!=null">
title=#{title}
</when>
<otherwise>
and views=#{views}
</otherwise>
</choose>

trim(where,set)

<select>
select * from mybatis.blog
<where>
<if test="title!=null">
and title=#{title}
</if>
<if test="auther!=null">
and auther=#{auther}
</if>
</where> </select>
<update id="updataBlog" parameterType="map">
update blog
<set>
<if test="title!=null">
title=#{title},
</if>
<if test="auther!=null">
auther=#{auther}
</if>
</set>
</update>

所谓的动态SQL,本质还是SQL语句,只是在SQL层面增加逻辑代码。

**SQL片段 **

  1. 使用SQL标签抽取公共部分
<sql id="if-title-auther">
<if test="title!=null">
and title=#{title}
</if>
<if test="auther!=null">
and auther=#{auther}
</if>
</sql>
  1. 在需要使用的地方使用include标签引用

select * from mybatis.blog

注意事项:

  • 最好基于单表来定义SQL片段
  • 不要存在where标签

Foreach

最新文章

  1. 关于Unity3D手机网游开发一些小看法
  2. U盘插入电脑后,提示需要格式化U盘如何解决?
  3. 我的ORM之十二 -- 支持的数据库及差别
  4. java开发中的一些工具软件
  5. [NOIP2010] 提高组 洛谷P1540 机器翻译
  6. hdu2955
  7. docker rabbitmq
  8. php的递归函数
  9. Error: theForm.submit is not a function !!
  10. Loadrunner11点击录制脚本无响应,IE页面弹不出——解决方案汇总
  11. 认识input输入框的placeholder属性
  12. 【Hibernate步步为营】--复合主键映射具体解释
  13. respondsToSelector
  14. Eclipse 基础操作与设置
  15. Java容器:List
  16. VS 编译通过后 链接提示 无法使用的外部符号
  17. Unity Editor 下创建Lua和Text文件
  18. Codeforces | CF1037D 【Valid BFS?】
  19. 第十四章 Java常用类
  20. unity, Collider2D.bounds的一个坑

热门文章

  1. CSS3伪类 :empty
  2. springboot+junit测试
  3. Maven配置文件中的版本使用-SNAPSHOT
  4. Linux常用命令(学习笔记)
  5. 题解 洛谷 P6349 【[PA2011]Kangaroos】
  6. 网易邮箱如何使用二次验证码/谷歌身份验证器/两步验证/虚拟MFA?
  7. Servlet学习之Tomcat控制台中文乱码问题
  8. JVM笔记-GC常用参数设置
  9. Python随机数函数
  10. Debug HashMap