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遍历
接口中方法:<