小言_互联网的博客

快速掌握mybatis动态SQL——看就懂

303人阅读  评论(0)

动态SQL

**概念:**它一般是根据用户输入或外部条件动态组合的SQL语句块。动态SQL能灵活的发挥SQL强大的功能、方便的解决一些其它方法难以解决的问题。相信使用过动态SQL的人都能体会到它带来的便利,然而动态SQL有时候在执行性能(效率)上面不如静态SQL,而且使用不恰当,往往会在安全方面存在隐患(SQL 注入式攻击)。

举例子:如果客户填了查询信息,则查询该条件;如果客户没填,则返回所有数据。

MyBatis的动态SQL包括以下几种元素

🏮

[快速搭建mybatis 直通车]((51条消息) Mybatis——快速搭建(1分钟直接复制搭建)_墨客小书虫的博客-CSDN博客)

数据库

CREATE TABLE `blog` (
  `id` varchar(50) NOT NULL COMMENT '博客id',
  `title` varchar(100) NOT NULL COMMENT '博客标题',
  `author` varchar(30) NOT NULL COMMENT '博客作者',
  `create_time` datetime NOT NULL COMMENT '创建时间',
  `views` int NOT NULL COMMENT '浏览量'
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

if

//需求1
List<Blog> queryBlogIf(Map map);
<!--    根据作者名字和博客名字来查询博客!-->
<!--    如果作者名字为空,那么只根据博客名字查询,反之,则根据作者名来查询-->
    <select id="queryBlogIf" resultMap="result">
        select  * from  blog
        where 1=1
        <if test="title!=null">
               and title=#{title}
        </if>
         <if test="author!=null">
            and author=#{author}
         </if>

    </select>

第二种写法 where 自动补充 and ,

第二个and 不能去,如果去掉第二个and ,如果第一个判断为空 它会补充,没有问题

但是,当两个同时满足时候,第二个判断没有and ,报错,所以第二个必须加and

<select id="queryBlogIf" resultMap="result">
    select  * from  blog
    <where>
        <if test="title!=null">
             title=#{title}
        </if>
        <if test="author!=null">
            and author=#{author}
        </if>
    </where>

set

比如我们前端需要修改博客信息,根据id 修改,但是有时候,我们只需要修改作者名,标题名不用修改。

有时候不需要修改作者名,标题名用修改

int updateBlog(Map map);
<update id="updateBlog">
        update  blog
  <set>
      <if test="title!=null">
          title=#{title}
      </if>
      <if test="author!=null">
          author=#{author}
      </if>
  </set>
    where id=#{id}
</update>

choose

满足一个就可以,按顺序匹配字段,但是只满足一个

List<Blog> queryBlogChoose(Map map);
<select id="queryBlogChoose" resultMap="result">
    select  * from  blog
    <where>
        <choose>
            <when test="title!=null">
                 title=#{title}
            </when>
            <when test="author!=null">
               and author=#{author}
            </when>
            <otherwise>
                and views=#{views}
            </otherwise>
        </choose>
    </where>
</select>

 

foreach

将数据库中前三个数据的id修改为1,2,3;
需求:我们需要查询 blog 表中 id 分别为1,2,3的博客信息

List<Blog> queryBlogForeach(Map map);
<select id="queryBlogForeach" resultMap="result">
    select  * from  blog
    <where>
        <foreach collection="ids" item="id" open="and ("  close=")"
                 separator="or">
            id=#{
   id}
        </foreach>
    </where>
</select>
<!--
    collection:指定输入对象中的集合属性
    item:每次遍历生成的对象
    open:开始遍历时的拼接字符串
    close:结束时拼接的字符串 
    separator:遍历对象之间需要拼接的字符串
    select * from blog where 1=1 and (id=1 or id=2 or id=3) 
  -->

转载:https://blog.csdn.net/weixin_45956631/article/details/125833696
查看评论
* 以上用户言论只代表其个人观点,不代表本网站的观点或立场