zoukankan      html  css  js  c++  java
  • Mybatis-08-动态SQL

    动态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标签引用

    注意事项:

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

    Foreach

    image-20200727000313341

  • 相关阅读:
    [转]SDRAM/DDR/DDR2/DDR3/DDR4
    Altera cyclone系列altlvds调试
    [转]关于Altera LVDS 经验分享
    [转]FPGA的GTP高速串行接口数据收发
    [转]ISE、vivado、QuartusII调用notepad++、UE汇总(整理)
    [转]vivado管脚分配:PACKAGE_PIN or LOC
    [转]如何使用WinDriver为PCIe采集卡装驱动
    【Docker系列教程之六】Docker的前世今生
    【Docker系列教程之五】如何构建Dockerfile
    【Docker系列教程之四】Dockerfile入门
  • 原文地址:https://www.cnblogs.com/CodeHuba/p/13499367.html
Copyright © 2011-2022 走看看