mybatis中动态sql的编写

1.mybatis中动态sql编写的场景

1.1 在实现多条件查询但是不确定其中的哪些条件不需要执行的情况

1.2 在根据传入的数组条件进行查询数据的时候

2.示例

2.1 在需要多条件查询时,可以使用mybatis的 if 标签自动判断是否添加该条件查询

<select id="queryByCondition" parameterType="com.zfj.entity.vo.StudentConditionVo" resultMap="map1">
        select * from student
        <where>
            <if test="name!=null and name !=''">
                and name=#{name}
            </if>
            <if test="gender!=null and gender!=''">
                and gender=#{gender}
            </if>
            <if test="telephone!=null and telephone!=''">
                and telephone=#{telephone}
            </if>
            <if test="minAge!=0 and maxAge==0">
                and age>#{minAge}
            </if>
            <if test="minAge==0 and maxAge!=0">
                and age&lt;#{maxAge}
            </if>
            <if test="minAge!=0 and maxAge!=0">
                and age between(#{minAge},#{maxAge})
            </if>
        </where>
    </select>

ps: where标签可以取代sql语句中的where 1=1

if 标签中的test属性是用来判断输入的值是否为空

2.2 在根据传入的数组条件进行查询数据的时候

<select id="queryByIds" parameterType="com.zfj.entity.vo.SidesVo" resultType="Student">
        select * from student
        <foreach collection="ids" item="id" open="where id in (" close=")" separator=",">
            #{id}
        </foreach>
    </select>

ps: <foreach>标签用来遍历数组,

collection 是传入的数组对象,

item 是对数组中遍历的对象取的别名,

open 是foreach标签 拼接在最前面的sql语句    "   where id in (   "    ,

close是该标签末尾拼接的sql语句   "  )  "     ,

separator是遍历对象之间的分隔符,这里的分隔符用"  ,  "。

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值