【MyBatis学习08】动态SQL

本文博客地址:http://blog.csdn.net/soonfly/article/details/63687917 (转载请注明出处)

动态SQL是Mybatis的牛B功能之一。以前写查询,最痛苦的就是拼SQL语句。如根据参数拼接查询条件,为空的不参与where条件;写where条件得保证第一条不能有and(所以还得写个1=1),写in你得注意逗号 。有时少打豆号,少打空格什么的,就给你个错误提示:You have an error in your SQL syntax;眼睛都能给找花。

比如前文提及的

<select id="searchByPrice" parameterType="Map" resultMap="productmap">
    select id p_id,productname p_name,price p_price from Product where
        price &gt;= #{minPrice} and price &lt;=#{maxPrice}
</select>

如果不设最小值查询,在不传minPrice的情况下,这条语句运行会有问题。所以严谨的做法是对输入参数进行为空判断后,再加入sql的条件中去。接下来就来看看下面几个知识点:

一、if语句

上文中要进行为空判断后才拼接进SQL查询中,我们在<where> 元素中用if进行判断,来构造where条件语句。
where 元素知道只有在一个以上的if条件有值的情况下才去插入“WHERE”子句。而且,若最后的内容是“AND”“OR”开头的,where 元素也会将它们去除。

<select id="searchByPrice" parameterType="Map" resultMap="productmap">
    select id p_id,productname p_name,price p_price from Product
    <where>
        <if test="minPrice!=null and minPrice!=''">
            <![CDATA[ and price >= #{minPrice}  ]]> 
        </if>
        <if test="maxPrice!=null and maxPrice!=''">
            <![CDATA[ and price <= #{maxPrice}  ]]> 
        </if>
    </where>
</select>

二、choose(when…otherwise)元素

choose 元素的作用就相当于JAVA中的switch语句,通常都是与when和otherwise搭配。当所有when中的条件都不满足时,会使用otherwise标签中的where条件。若查询要求改成这样:如果minPrice和maxPrice参数为空,就不加入到条件中去,如果两个都为空,系统默认查询价格在2000-3000之间的产品

<select id="searchByPrice" parameterType="Map" resultMap="productmap">
        <!-- xml格式处理sql语句时,经常用到< ,<=,>,>=等符号,会引起xml格式的错误,需要替换 -->
        select id p_id,productname p_name,price p_price from Product where 1=1
        <choose>
            <when test="minPrice!=null and minPrice!=''">
                <![CDATA[ and price >= #{minPrice}  ]]> 
            </when>
            <when test="maxPrice!=null and maxPrice!=''">
                <![CDATA[ and price <= #{maxPrice}  ]]> 
            </when>
            <otherwise>
                <![CDATA[ and price <= 3000 and price>=2000 ]]> 
            </otherwise>
        </choose>
    </select>

三、trim元素

与trim元素配合使用的属性有
prefix和suffix:给指定内容加上前缀或后缀
prefixOverrides和suffixOverrides :忽略指定内容的前缀和后缀
可以利用trim来代替where元素的功能。

<select id="searchByPrice" parameterType="Map" resultMap="productmap">
    select id p_id,productname p_name,price p_price from Product
    <trim prefix="where" prefixOverrides="and|or">
        <if test="minPrice!=null and minPrice!=''">
            <![CDATA[ and price >= #{minPrice}]]>
        </if>
        <if test="maxPrice!=null and maxPrice!=''">
            <![CDATA[ and price <= #{maxPrice}]]>
        </if>
    </trim>
</select>

四、foreach元素

在构建 in 条件语句的时候,foreach元素的功能是非常强大的。它就相当于java中的foreach,遍历一个集合,按规则生成拼接字符串。
foreach元素的属性主要有itemindexcollectionopenseparatorclose
item表示集合中每一个元素进行迭代时的别名,index指定一个名字,用于表示在迭代过程中,每次迭代到的位置,open表示该语句以什么开始,separator表示在每次进行迭代之间以什么符号作为分隔符,close表示以什么结束。
接口:

public List<Product> searchByPrice(@Param(value="ids") List<Integer> ids) throws Exception;

XML:

<select id="searchByPrice" parameterType="List" resultMap="productmap">
        select id p_id,productname p_name,price p_price from Product where
        cateid in
        <if test="ids!=null">
            <foreach collection="ids" index="key"  item="value" open="("
                close=")" separator=",">
                <!-- 遍历拼接的串 -->
                #{value}
            </foreach>
        </if>
    </select>

调用:

List<Integer> list =new ArrayList<Integer>();
list.add(1);
list.add(2);
List<Product> tmpuser=mp.searchByPrice(list);

五、set元素

set元素主要是用在更新操作的时候,会在包含的语句前输出一个set。
接口:

public void Update(Product product) throws Exception;

XML:

<update id="Update" parameterType="Product">
    <if test="id !='' and id != null">
        update product 
        <set>
            <if test="productname !=null and productname!=''">
                productname=#{productname},
            </if>
            <if test="price !=null and price!=''">
                price=#{price},
            </if>
            <if test="cateid !=null and cateid!='' and cateid &gt; 0">
                cateid=#{cateid}
            </if>
        </set>
        where id=#{id}
    </if>
</update>

六、bind元素

bind元素主要是用创建一个变量并赋值
如:在之前使用模糊查询时,因为要加入%,所以没有使用占位符#{},而是用拼接符${}

public List<User> findByName(@Param(value="searchkey") String searchkey) throws Exception;
<select id="findByName" parameterType="String" resultType="twm.mybatisdemo.pojo.User">
    select * from user where username like '%${searchkey}%'
 </select>

有了bind元素,我们可以改成这样

<select id="findByName" parameterType="String" resultType="twm.mybatisdemo.pojo.User">
    <bind name="likestr" value="'%'+ searchkey +'%'"></bind>
    select * from user where username like #{likestr}
</select>

本文博客地址:http://blog.csdn.net/soonfly/article/details/63687917 (转载请注明出处)

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值