mybatis动态SQL(六)

本文详细介绍了MyBatis中动态SQL的使用,包括if、choose、when、otherwise、trim和foreach等标签的应用。通过实例展示了如何在查询语句中根据参数动态添加条件,如模糊查询和多条件组合查询,以及如何使用foreach进行多ID查询。通过对这些标签的掌握,可以灵活地构建复杂的SQL映射文件。
摘要由CSDN通过智能技术生成

动态SQL常用控制语句

  • if
  • choose (when, otherwise)
  • trim (where, set)
  • foreach

1、if语句使用

可以使用if进行动态模糊查询,我们修改原有的模糊查询映射代码

<!--模糊查询-->
<select id="findByName" parameterType="user" resultMap="userMap">
    select * from user where 1=1
    <if test="userName != null and userName != ''">
        and username like #{userName}
    </if>
    <if test="userAddress != null">
        and address like #{userAddress}
    </if>
</select>

测试代码如下:

/**
 * 模糊动态查询
 */
@Test
public void testFindByName(){
    User u = new User();
    u.setUserName("%王%");
    u.setUserAddress("%成都%");
    List<User> users = userDao.findByName(u);
    for (User user:users){
        System.out.println(user);
    }
}

2、where标签使用

上面我们未使用where标签所以使用1=1作为条件,使用where标签后调整如下

<!--模糊查询-->
<select id="findByName" parameterType="user" resultMap="userMap">
    select * from user
    <where>
        <if test="userName != null and userName != ''">
            and username like #{userName}
        </if>
        <if test="userAddress != null">
            and address like #{userAddress}
        </if>
    </where>

</select>

3、foreach标签使用

我们新增一个UserDao接口中新增findByIds方法

配置我们的映射文件如下:

<!--动态查询-多id查询-->
<select id="findByIds" parameterType="com.shenqiang.domain.QueryVo" resultMap="userMap">
    select * from user
    <where>
        <if test="ids != null and ids.size()>0">
            <foreach collection="ids" item="uid" open="id in (" separator="," close=")">
                #{uid}
            </foreach>
        </if>
    </where>
</select>

这个使用foreach时相当于使用了拼接我们将我们的查询语句拼接进去。

collection:代表要遍历的集合元素,注意编写时不要写#{}

open:代表语句的开始部分

close:代表结束部分

item:代表遍历集合的每个元素,生成的变量名

sperator:代表分隔符

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值