mybatis—动态sql

一,概述

动态SQL就是为了在SQL层面实现逻辑代码,不用去拼接SQL了。换句话说就是根据不同条件生成不同的SQL语句,简化开发。

1.1整体比较-类中实现

public class useSql {
    public String findContactByPage2(@Param("start") int start, @Param("pageSize") int pageSize,@Param("name") String name, @Param("max") String max, @Param("min")String min) {
        String sql = "select * from contact where 1=1 ";
        if (name != null && name.trim().length() > 0) {
            sql += "and name like concat('%',#{name},'%')";
        }
        if (max != null && max.trim().length() > 0) {
            sql += " and age<#{max}";
        }
        if (min != null && min.trim().length() > 0) {
            sql += " and age>#{min}";
        }
        sql += "limit #{start},#{pageSize}";

        return sql;
    }

1.2整体比较–mapper实现

<select id="queryBlogIF" 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>

二,if语句

在这里插入图片描述

上述代码存在sql注入问题。

三,if + where 语句

where标签就是去掉,第一条以and 或者or开头的语句,后续的就不用会写了
在这里插入图片描述
那如果上面两个条件都不满着呢???那就自动吧where去掉。

四,choose(when,otherwise)语句

有时候,我们不想使用所有语句,就想使用多个语句中的一个,那就要用它,例如java中的switch-case语句。
在这里插入图片描述

五,set语句

在这里插入图片描述
两个作用:

  • 当做set连接
  • 自动取消多余的逗号

一个注意点

  • 中间逗号不能少

六,SQL片段

功能:将一些重复的部分抽离出来,方便复用!

  • 使用SQL标签抽取公共的部分
<sql id="updateblog">
        <if test="title != null">
            title = #{title},
        </if>
        <if test="author != null">
            author = #{author}
        </if>
    </sql>
  • 在需要使用的地方使用include引用即可
    <update id="updateBlog" parameterType="map">
        update blog
        <set>
            <include refid="updateblog"></include>
        </set>
            where id = #{id}
    </update>

注意点:

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

七,foreach

功能:对集合进行遍历(尤其是in条件语句中)

例如:

select * from user where id = 1 or id = 2 or id = 3

select * from user where id in(1,2,3)
<select id="selectUserByListId" parameterType="com.ys.vo.UserVo" resultType="com.ys.po.User">
    select * from user
    <where>
        <!--
            collection:指定输入对象中的集合属性
            item:每次遍历生成的对象
            open:开始遍历时的拼接字符串
            close:结束时拼接的字符串
            separator:遍历对象之间需要拼接的字符串
            select * from user where 1=1 and (id=1 or id=2 or id=3)
          -->
        <foreach collection="ids" item="id" open="and (" close=")" separator="or">
            id=#{id}
        </foreach>
    </where>
</select>

在这里插入图片描述

总结

动态SQL就是拼接,先写原生SQL,然后通过动态SQL的规则进行改造

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值