从零开始学Mybatis(十)——动态SQL

  • 什么是动态sql

通过mybatis提供的各种标签方法实现动态拼接sql的过程

  • If标签

根据用户名和用户类别查询用户时,我们编写的sql语句如下

<select id="queryByNameAndProfession" resultType="demo2.domain.Customer" parameterType="String">
    SELECT * FROM customer WHERE cust_name = #{custName} and cust_profession =#{custProfession}
</select>

有可能传入的用户名或用户类别为空,那么可能导致我们编写的sql语句出问题

那么我们就可以使用mybatis提供的if标签来解决这个问题

我们可以使用if标签来进行非空判断,动态地拼接sql语句

<select id="queryByNameAndProfession" resultType="demo2.domain.Customer" parameterType="String">
    SELECT * FROM customer WHERE
    <if test="custName!=null and custName!=''">
        cust_name = #{custName}
    </if>
    <if test="custProfession !=null and custProfession !=''">
        and cust_profession =#{custProfession}
    </if>
</select>

我们仔细看这个sql语句就会发现,如果第一个条件不成立(即custName为空),那么我们拼接出来的sql语句就是 SELECT * FROM customer WHERE  and cust_profession =#{custProfession} ,这将导致我们sql执行时报错,因此mybatis给出了where标签代替where关键字的解决方案

  • Where标签

和if标签搭配使用时,会去掉紧跟where关键字后面的and关键字

<select id="queryByNameAndProfession" resultType="demo2.domain.Customer" parameterType="String">
    SELECT * FROM customer
    <where>
        <if test="custName!=null and custName!=''">
            cust_name = #{custName}
        </if>
        <if test="custProfession !=null and custProfession !=''">
            and cust_profession =#{custProfession}
        </if>
    </where>
</select>

如果第一个条件不成立,拼接第二个条件时会把第二个条件的and关键字去掉,则拼接出来的sql语句是SELECT * FROM customer WHERE  cust_profession =#{custProfession}

  • Foreach标签

当我们的查询条件的值为我们指定的值当中,即使用in关键字,那么使用foreach标签。

<select id="queryInId" resultType="demo2.domain.Customer" >
    SELECT * FROM customer WHERE cust_id in(2,3,4)
</select>

在foreach标签中,我们可以以数组、List、VO对象的形式给出指定的值。

数组形式示例

 

List形式

VO对象形式

 

 

  • Sql片段 

Sql中可将重复的sql语句提取出来,使用时用include标签根据sql片段的id引用即可,最终达到sql重用的目的。

 

抽取sql片段后

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值