动态sql

目录

1.什么是动态sql:

1.2为什么使用动态sql:

1.3mybatis中动态sql标签有哪些?

2.if标签--单条件判断

3.choose标签 多条件分支判断

4.where标签


1.什么是动态sql:

根据参数的值,判断sql的条件。

name!=null address
select * from 表名 where name=#{name} and address=#{address}
name==null
select * from 表名

1.2为什么使用动态sql:

1.3mybatis中动态sql标签有哪些?

2.if标签--单条件判断

 //如果name不为null则按照name查询 如果为null则查询所有
    public List<Account> findByCondition(@Param("name")String name,@Param("money") Double money);

 <select id="findByCondition" resultType="com.ykq.entity.Account">
        select * from account where 1=1
        <if test="name!=null and name!=''">
             and  name=#{name}
        </if>
        <if test="money!=null">
             and  money=#{money}
        </if>
    </select>

3.choose标签 多条件分支判断

<select id="findByCondition02" resultType="com.ykq.entity.Account">
        select * from account where 1=1
        <choose>
             <when test="name!=null and name!=''">
                 and  name=#{name}
             </when>
            <when test="money!=null">
                and  money=#{money}
            </when>
            <otherwise>
                and isdeleted=0
            </otherwise>
        </choose>
    </select>

4.where标签

我们观察到上面的sql都加了 where 1=1 ,如果不使用where 1=1 那么你的动态sql可能会出错。 我们能不能不加where 1=1呢! 可以 那么我们就可以使用where标签,作用:可以自动为你添加where关键字,并且可以帮你去除第一个and |or

 <select id="findByCondition" resultType="com.ykq.entity.Account">
        select * from account
        <where>
            <if test="name!=null and name!=''">
                 and  name=#{name}
            </if>
            <if test="money!=null">
                 and  money=#{money}
            </if>
        </where>
    </select>

评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值