Mybatis--动态SQL

案例一(where和if的使用):根据名字和成绩来查询人数,名字为模糊查询。

    <select id="total" resultType="Integer">
        select count(*) from student
        <where>
            <if test="name!=null and name!=''">and name like concat('%',#{name},'%')</if>
            <if test="score!= null and score>=0">and score = #{score}</if>
        </where>
    </select>

 注意,where的作用在于可以在if语句都为空时,才会拼接SQL语句。不在需要之前的where 1=1。

案例二(choose,when,otherwize的使用)

与案例一不同的是,案例一是只要test属性表达式为true,那么就会执行SQL语句。但是,当我们需要从多个条件中只选一个条件执行时(即使可能多个条件满足,比如我们Java中的Switch...catch...default),那么我们就可以用这些元素。

<select id="findActiveBlogLike"
     resultType="Blog">
     SELECT * FROM BLOG WHERE state = ‘ACTIVE’
 <choose>
     <when test="title != null">
         AND title like #{title}
     </when>
     <when test="author != null and author.name != null">
         AND author_name like #{author.name}
     </when>
     <otherwise>
         AND featured = 1
     </otherwise>
 </choose>
</select>

本案例是使用了choose元素进行SQL语句的拼装,当第一个when为true时就只拼装第一个,否则判断第二个,以此类推。如果所有的when都为false,那么就只拼装otherwise。

案例三(trim,where的使用)

    <select id="queryByName" parameterType="Map" resultMap="studentMap">
		select * from `student`
		<trim prefix="where" prefixOverrides="and">
			<if test="name!=null and name!=''">and name like concat('%',#{name},'%')</if>
		</trim>
		limit #{start},#{end}
	</select>

注意,当trim内的条件不满足时就相当于没有。

案例四(set的使用)

<update id="updateAuthorIfNecessary">
     update Author
     <set>
         <if test="username != null">username=#{username},</if>
         <if test="password != null">password=#{password},</if>
         <if test="email != null">email=#{email},</if>
         <if test="bio != null">bio=#{bio}</if>
     </set>
     where id=#{id}
</update>

注意,当test语句都不满足时,不会被组装。 

案例五(foreach的使用)

    <delete id="deleteMore">
		delete from student where id in
		<foreach collection="list" item="item_id" separator="," open="(" close=")">
			#{item_id}
		</foreach>
	</delete>

比如这里的批量删除。 

案例六(bind的使用):

<select id="selectBlogsLike" resultType="Blog">
     <bind name="pattern" value="'%' + _parameter.getTitle() + '%'" />
     SELECT * FROM BLOG
     WHERE title LIKE #{pattern}
</select>

它的方便性一个时可以进行文本代替,另一个是便于移植。

 

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值