【Mybatis 框架(自学)】Day08--2022/3/18

动态SQL

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

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

if:

<!--
	动态SQL之if语句:
-->

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

choose(when,otherwise):

<!--
	动态SQL之chosse语句:当一个条件不满足时,必定走when、otherwise的其中一条,只能选择其中一个
-->

<select id="queryByWhen" parameterType="blog" resultType="Blog">
      select * from blog where 1=1
<choose>
     <when test="title != null">
           and title like concat('%',#{title},'%')
     </when>
     <when test="author != null">
           and author = #{author}
      </when>
</choose>
    </select>

trim(where,set):

<!--
	where:自动在SQL语句中加上前缀where,所以在编写SQL的过程中,可以将where省略
-->

<select id="queryByWhere" parameterType="Blog" resultType="blog">
     select * from blog
    <where>
        <if test="title != null">
            and title = #{title}
        </if>
        <if test="author != null">
            and author = #{author}
        </if>
    </where>
</select>
<!--
	set:自动在SQL语句中前置set,可以进行多条或单条的修改,如果SQL有多条修改条件
		实际执行时,只修改一条,则自动省略此修改语句后面的“,”号
-->
<update id="updateBlog" parameterType="Blog">
    update blog
   <set>
      <if test="title !=null">
           title =#{title},
      </if>
      <if test="author !=null">
           author=#{author}
       </if>
   </set>
        where views =#{views}
</update>
 <!--
	Trim:此标签的最主要用法就是前置和省略,当SQL语句编写完毕时,根据情况会有前置where
		 后置and/or/,等等,不同环境有不同用法,非常方便
-->
<select id="queryByTrim" parameterType="Blog" resultType="blog">
        select * from blog
  <trim prefix="where" prefixOverrides="and">
       <if test="title != null">
              title like concat('%',#{title},'%')
       </if>
       <if test="author != null">
              author = #{author}
       </if>
   </trim>
</select>
<!--
	一般来讲,正常的SQL语句是:查询的表名 where 条件 and 条件,加了tirm标签之后
			可以前置where,后置省略and
-->

foreach:

<!--
	foreach:其中open是前置拼接,close是后置拼接,separator是分隔符,index为下标索引,
			item对应的是SQL的参数,collection是需要传递进SQL的值
-->
<select id="findByList" parameterType="java.util.List" resultType="Blog">
        select * from blog where views in
   <foreach collection="list" item="views" index="index" open="(" separator="," close=")">
        #{views}
    </foreach>
</select>



<select id="findByMap" parameterType="java.util.Map" resultType="Blog">
    select * from blog where author=#{author} and views in
     <foreach collection="ids" item="views" index="index"  open="(" separator="," close=")">
           #{views}
     </foreach>
</select>

SQL拼接:

做了解,百度

posted @   VVS,冷漠的心  阅读(25)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· DeepSeek 开源周回顾「GitHub 热点速览」
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET 10首个预览版发布:重大改进与新特性概览!
· AI与.NET技术实操系列(二):开始使用ML.NET
· 单线程的Redis速度为什么快?

囚鸟该如何超越今生?

点击右上角即可分享
微信分享提示