mybatis—动态sql
一,概述
动态SQL就是为了在SQL层面实现逻辑代码,不用去拼接SQL了。换句话说就是根据不同条件生成不同的SQL语句,简化开发。
1.1整体比较-类中实现
public class useSql {
public String findContactByPage2(@Param("start") int start, @Param("pageSize") int pageSize,@Param("name") String name, @Param("max") String max, @Param("min")String min) {
String sql = "select * from contact where 1=1 ";
if (name != null && name.trim().length() > 0) {
sql += "and name like concat('%',#{name},'%')";
}
if (max != null && max.trim().length() > 0) {
sql += " and age<#{max}";
}
if (min != null && min.trim().length() > 0) {
sql += " and age>#{min}";
}
sql += "limit #{start},#{pageSize}";
return sql;
}
1.2整体比较–mapper实现
<select id="queryBlogIF" parameterType="map" resultType="Blog">
select * from blog where 1= 1
<if test="title != null">
and title = #{title}
</if>
<if test="author != null">
and author = #{author}
</if>
</select>
二,if语句
上述代码存在sql注入问题。
三,if + where 语句
where标签就是去掉,第一条以and 或者or开头的语句,后续的就不用会写了
那如果上面两个条件都不满着呢???那就自动吧where去掉。
四,choose(when,otherwise)语句
有时候,我们不想使用所有语句,就想使用多个语句中的一个,那就要用它,例如java中的switch-case语句。
五,set语句
两个作用:
- 当做set连接
- 自动取消多余的逗号
一个注意点
- 中间逗号不能少
六,SQL片段
功能:将一些重复的部分抽离出来,方便复用!
- 使用SQL标签抽取公共的部分
<sql id="updateblog">
<if test="title != null">
title = #{title},
</if>
<if test="author != null">
author = #{author}
</if>
</sql>
- 在需要使用的地方使用include引用即可
<update id="updateBlog" parameterType="map">
update blog
<set>
<include refid="updateblog"></include>
</set>
where id = #{id}
</update>
注意点:
- 最好基于单表定义SQL片段,提高片段的可重复性
- 在SQL片段中最好不要包括where
七,foreach
功能:对集合进行遍历(尤其是in条件语句中)
例如:
select * from user where id = 1 or id = 2 or id = 3
select * from user where id in(1,2,3)
<select id="selectUserByListId" parameterType="com.ys.vo.UserVo" resultType="com.ys.po.User">
select * from user
<where>
<!--
collection:指定输入对象中的集合属性
item:每次遍历生成的对象
open:开始遍历时的拼接字符串
close:结束时拼接的字符串
separator:遍历对象之间需要拼接的字符串
select * from user where 1=1 and (id=1 or id=2 or id=3)
-->
<foreach collection="ids" item="id" open="and (" close=")" separator="or">
id=#{id}
</foreach>
</where>
</select>
总结
动态SQL就是拼接,先写原生SQL,然后通过动态SQL的规则进行改造