关于Mybatis中的动态SQL语句

Mybatis中实现动态SQL是通过以下几个标签实现的

<if> </if>
<where> </where>
<foreach> </foreach>
<sql> </sql>

if标签

使用的语法规则和JSTL中是一样的

其中的test属性放我们判断的条件

如果条件成立则执行标签内部的代码
如果不成立则不执行

比如

<if test="username!=null">
and username=#{username}
</if>

where标签

比如我们现在想根据username来查询一个用户的全部信息

那么我们使用if标签这样写

<select id="selectUserByCondition" parameterType="user" resultType="user">
select * from user where 1=1
<if test="username!=null">
    and username=#{username}
</if>
</select>

我们发现有一个where 1=1
因为如果我们不写这个 1=1 那么当username为null的时候
我们的sql语句就变成了

select * from user where

这显然是不符合语法规则的

但是要写1=1又显得很多余

这时候我们的where标签就出现了

我们只需要这样写就行了

<select id="selectUserByCondition" parameterType="user" resultType="user">
select * from user
<where>
    <if test="username!=null">
        and username=#{username}
     </if>
</where>
</select>

sql标签

有一些语句我们会重复的写很多次

比如

select * from user

sql标签可以将这段语句封装起来

类似mysql中的存储过程

比如我们将这段语句封装起来 并起名为defaultSql

<sql id="defaultSql">
    select * from user
</sql>

只要在需要使用的地方引入即可

比如

<select id="selectAll" resultType="user">
    <include refid="defaultSql"></include>
</select>

就像我们写一些重用的css,js也可以到处引入一样的

不过这里有个注意事项 我们sql标签中的语句一定不要加分号

否则我们举一个例子

比如我们写一个根据id查询用户的sql语句

<select id="findById" resultType="user" parameterType="int">
<include refid="defaultSql"></include>
where id = #{uid}
</select>

如果加了分号
那么sql语句就变成了

select * from user ; 
where id = xxx 

显然语法错误了

foreach标签

比如现在我们需要查询多个id对应的多个用户

那么sql语句我们可以写成

select * from user
where id in (46,48,52);

那么在Mybatis中要怎么实现呢?

这时候我们的foreach标签就派上用场了

<select id="selectUserByIdList" resultType="user" parameterType="queryvo">
    select * from user
    <where>
        <if test="idList!=null and idList.size()>0">
            <!--collection是要遍历的集合 item是每个元素 open是以什么开始 close是以什么结束-->
            <!--
                我们这样写 最终是为了拼接成
                select * from user where 其他条件 and id in (id1,id2,...)
            -->
            <foreach collection="idList" item="uid" open="and id in(" close=")" separator=",">
                #{uid}
            </foreach>
        </if>
    </where>
</select>

参数说明:

queryvo中有一个

private List<Integer> idList;
疑问

到这里我们会有一些疑问

为什么 我们这里多写了 and 也不会报错

按我们这样写 拼接出来的sql会是

select * from user
where and id in (id1,id2,...)

这显然是不符合语法的

我猜测是where标签的功劳

如果标签返回的内容是以AND 或OR 开头的,where标签会将多余的and或or剔除掉。

这个坑等 时机成熟

运气好翻源码啥的看到了 再补吧。。。

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值