动态sql及分页插件及sql自动生成

1.动态sql的语句

(1)所谓动态sql即SQL语句拼接拼接方式分为:

①if 判断语句 ②where 语句 ③choose when otherwise ④trim 替换语句 ⑤forEach 循环语句

案例使用表:

DROP TABLE IF EXISTS `account`;
CREATE TABLE `account` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `name` varchar(255) DEFAULT NULL,
  `money` double DEFAULT NULL,
  `isdeleted` tinyint(4) DEFAULT NULL,
  `created` datetime DEFAULT NULL,
  `updated` datetime DEFAULT NULL,
  PRIMARY KEY (`id`)
)

(2)使用if 语句进行mybatis内sql拼接

<!--判断name是否为空,若空则执行if内语句。where 1=1 为了使第一个语句内的and不会使sql报错
	concat将括号内的进行拼接。
-->
	<select id="getAccount" resultType="Account">
        select * from account where 1=1
        <if test="name!=null and name != ''">
            and name like concat('%',#{
   name},'%')
        </if>
    </select>

(3)使用where语句代替where 1=1

<!--使用where会代替之前语句中的where 1=1.。。。它会自动将第一条语句中的and去掉,再加上where
-->
	<select id="getAccount" resultType="Account">
        select * from account where 1=1
        <if test="name!=null and name != ''">
            and name like concat('%',#{name},'%')
        </if>
    </select>

(4)使用choose语句进行sql拼接

<!-- 
    choose与Java中的switch用法类似。进行when中test为判断语句,,一旦满足条件执行when中的语句,choose就会结束,不会执行其他when或者otherwise....
    otherwise表示当前面的when的判断调教全都不满足时执行的语句
    -->
<select id="getAccount" resultType="Account">
        select * from account 
        <when>
        <choose>
            <when test="name !=null and name!=''">
                and name like concat('%',#{
   name},'%')
            </when>
            <otherwise>
                and isdeleted=2
            </otherwise>
        </choose>
        </when>
    </select>

(5)使用trim语句进行语句替换

 <!--trim表示替换。。prefix表示前置替换,prefixOverrides为前置要替换的。下例是将第一个and替换为where。
        suffix为后置替换,suffixOverrides表示后置要替换的,即将最后一个,,替换为,,
    -->
    <select id="getAccount" resultType="Account">
        select * from account
        <trim prefix="where" prefixOverrides="and" suffix="" suffixOverrides="">
            <choose>
                <when test="name !=null and name !=''">
                    and name like concat('%',#{name},'%')
                </when>
                <when test="money!=null and money!=''">
                    and money=#{money}
                </when>
                <otherwise>
                    and isdeleted=2
                </otherwise>
            </choose>
        </trim>
    </select>

(6)使用foreach遍历

接口中方法:<

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值