MyBatis动态SQL设置

动态SQL,也就是说在配置文件里面可以实现判断、循环的处理。
1、if语句
所谓的if语句指的就是更新或查询语句的时候可以对传入内容进行判断操作。

<select id="findAllByTitle" parameterType="News" resultMap="NewsMap"> 
    SELECT nid,title,pub_date FROM news 
    <if test="title != null"> 
        WHERE title=#{title} 
    </if> 
</select>

在分页上使用动态SQL 处理

    <select id="findAllSplit" parameterType="java.util.Map" resultMap="NewsMap" useCache="false">
    SELECT nid,title,pub_date FROM news
    <if test="column != null">
        WHERE ${column} LIKE #{keyWord}
    </if>
        LIMIT #{start},#{lineSize}
</select>
    <select id="findAllSplit" parameterType="java.util.Map" resultMap="NewsMap" useCache="false">
    SELECT nid,title,pub_date FROM news
    <if test="column != null and keyWord !=null">
        WHERE ${column} LIKE #{keyWord}
    </if>
    <if test="start &gt; 0 and lineSize &gt; 0 ">
        LIMIT #{start},#{lineSize}
    </if>
</select>

“: & g t ; ” 等于 “>”
2、choose 语句
使用if 语句的确可以进行简单的判断,但是如果要想进行多条件判断,就需要通过choose 语句完成,相当于java中的which。

<select id="findAllByTitle" parameterType="News" resultMap="NewsMap">
    SELECT nid,title,pub_date FROM news
    <where>
        <choose>
            <when test="nid != null and title != null">
                nid=#{nid} AND title=#{title}
            </when>
            <when test="nid != null">
                nid=#{nid}
            </when>
            <when test="title != null">
                title=#{title}
            </when>
        </choose>
    </where>
</select>

3、set 语句
set 语句主要出现在更新处理上,它出现的主要意义在于,可以利用set 语句在UPDATE 编写上自动出现SET 标记而已。

<update id="doUpdate" parameterType="News">
    UPDATE news
        <set>
            title = #{title} ,
            <if test="pubdate != null">
                pub_date = #{pubdate} ,
            </if>
        </set>
        <where>
            <if test="nid != null">
                nid=#{nid}
        </if>
    </where>
</update>

4、foreach 语句

<delete id="doRemoveBatch" parameterType="Integer">
    DELETE FROM news
    <where>
        nid IN
        <foreach collection="array" open="(" close=")" separator="," item="ele">
            #{ele}
        </foreach>
    </where>
</delete>
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值