mybatis动态sql中where、set、if 、for循环使用

18 篇文章 1 订阅
11 篇文章 0 订阅

where-if

<select id="listBySearch" resultType="java.lang.Integer">
        SELECT id FROM hospital 
        <where>
	        <if test="search.province!=null and search.province!=''">
	             province=#{search.province}
	        </if>
	        <if test="search.city!=null and search.city!=''">
	            AND city=#{search.city}
	        </if>
        </where>
    </select>

test里面是条件 多个条件用and连接,if外加where标签后如果第一个if不符合条件,第二个if会自动去掉开头的 AND (不会去掉结尾的AND)SQL:

SELECT id FROM hospital  WHERE city='xxx'

set-if


 <update id="updateHospitalById">
        UPDATE user
		 <set >
		      <if test="name != null" >
		        name = #{name},
		      </if>
		      <if test="sex != null" >
		        sex = #{sex},
		      </if>
		</set>
        WHERE type = #{type}
    </update>

test里面是条件 多个条件用and连接,if外加set标签后编译出来的sql会去掉sex = #{sex},中的,,如果条件都满足则SQL为:

UPDATE user SET name='xxx' ,sex='xxx' WHERE type='xxx'

for

<select id="listByIds" resultType="hospital">
        SELECT * FROM hospital  
        <foreach collection="list" item="item" index="index" open="WHERE id IN (" separator="," close=")">
            #{item.id}
        </foreach>
    </select>

collection:要循环的集合
item:当前迭代对象
index:当前迭代次数
open:以什么字符开始
separator:分割符
close:以什么结束

如果list 的size为4,id分别为 1,2,3,4则SQL为:

SELECT * FROM hospital WHERE id IN(1,2,3,4)
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值