Mybatis 动态 SQL

本文介绍了MyBatis中的几种动态SQL标签,包括if用于条件判断,where处理多条件避免SQL语法错误,set在更新语句中设置条件,trim自定义前缀和后缀修剪,choose实现类似if-else的功能,以及foreach用于遍历集合构建in条件。这些标签帮助优化和简化了SQL查询的编写。
摘要由CSDN通过智能技术生成

一、if 标签

配置文件代码

 <!--查询(if) 如果 name 为空,则查询所有,如果不为空, 则进行模糊查询-->
        <select id="listCategoryIf" resultType="Category">
            select * from category_
            <if test="name!=null">
                where name like concat('%',#{name},'%')
            </if>        
        </select>

查询所有

// 查询所有数据
	public static void ListAll(SqlSession session) {
		List<Category> cs = session.selectList("listCategoryIf");
		for (Category c : cs) {
			System.out.println(c.getName());
		}
	}

if模糊查询

// if模糊查询
	public static void ifSelectListByName(SqlSession session, String name) {
		Map<String, Object> map = new HashMap<>();
		map.put("name", name);
		List<Category> categories = session.selectList("listCategoryIf", map);
		for (Category category : categories) {
			System.out.println(category.getName());
		}
	}

注意:

普通的模糊查询是直接赋予参数 ,不需要创建 Map 类,而 if模糊查询 需要创建 Map 类 ,并将name 传到 Map 中,最后将 map 当作参数传入相应的标签中。

从上面可以看到,两种查询方法使用的是同一个查询标签,区别是  是否传入参数

可以想到 Map 类是传递 参数的,并且可以传递多个参数。

二、where 标签

多条件的矛盾

<select id="listCategory" resultType="Product">
        select * from category_
        <if test="name!=null">
            where name like concat('%',#{name},'%')
        </if>        
        <if test="price!=0">
            and price > #{price}
        </if>        
    </select>

这样可以判断多个条件,但是当 name 为空时,sql 语句就会为

select * from category_ and price > x

这样就会报错。

而 where 标签则可以解决这个问题

<select id="listProduct" resultType="Product">
        select * from product_
        <where>
            <if test="name!=null">
                and name like concat('%',#{name},'%')
            </if>        
            <if test="price!=null and price!=0">
                and price > #{price}
            </if>
        </where>     
    </select>

当任何条件 都不成立 时,where 不会在 sql 语句中出现;

当有任何一个条件 成立 时, 会自动去掉多出来的 and 或者 or。

三、set 标签

与 where 标签类似,在 update 标签中碰到多个条件的时候使用

<update id="updateProduct" parameterType="Product" >
        update product_
        <set>
            <if test="name != null">name=#{name},</if>
            <if test="price != null">price=#{price}</if>
              
        </set>
         
         where id=#{id}   
    </update>

四、trim 标签

trim 标签用来定制想要的功能,可以定制 where 标签 和 set 标签

<select id="listProduct" resultType="Product">
        select * from product_
        <trim prefix="WHERE" prefixOverrides="AND |OR ">
            <if test="name!=null">
                and name like concat('%',#{name},'%')
            </if>        
            <if test="price!=null and price!=0">
                and price > #{price}
            </if>
        </trim>      
    </select>
     
    <update id="updateProduct" parameterType="Product" >
        update product_
        <trim prefix="SET" suffixOverrides=",">
            <if test="name != null">name=#{name},</if>
            <if test="price != null">price=#{price}</if>
              
        </trim>
         
         where id=#{id}   
    </update>

五、choose 标签

Mybatis 中没有 else 标签 ,用 when otherwise 来达到 if else 的效果

<select id="listProduct" resultType="Product">
              SELECT * FROM product_
              <where>
                <choose>
                  <when test="name != null">
                    and name like concat('%',#{name},'%')
                  </when>          
                  <when test="price !=null and price != 0">
                    and price > #{price}
                  </when>                
                  <otherwise>
                    and id >1
                  </otherwise>
                </choose>
              </where>
        </select>

六、foreach 标签

通常与 in 联系,相当于 for 循环

<select id="listProduct" resultType="Product">
          SELECT * FROM product_
            WHERE ID in
                <foreach item="item" index="index" collection="list"
                    open="(" separator="," close=")">
                    #{item}
                </foreach>
    </select>

七、bind 标签

相当于在模糊查询的基础上 做了一次字符串拼接

<!-- 本来的模糊查询方式 -->
<!--         <select id="listProduct" resultType="Product"> -->
<!--             select * from   product_  where name like concat('%',#{0},'%') -->
<!--         </select> -->
             
        <select id="listProduct" resultType="Product">
            <bind name="likename" value="'%' + name + '%'" />
            select * from   product_  where name like #{likename}
        </select>

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值