1、动态sql:
sql的内容是变化的,可以根据条件获取到不同的sql语句。
主要是where部分发生变化。
2、动态sql的实现
使用的是mybatis提供的标签, <if> ,<where>,<foreach>
1) <if>是判断条件的,
语法<if test="判断java对象的属性值">
部分sql语句
</if>
<!-- if
<if:test="使用参数java对象的属性值作为判断条件,语法 属性=XXX值">
-->
<select id="selectStudentIf" resultType="com.bjpowernode.domain.Student">
select <include refid="studentSqlOne" /> from student
where id > 0
<if test="name !=null and name !='' ">
and name = #{name}
</if>
<if test="age > 0">
or age > #{age}
</if>
</select>
注:这里的 where 条件中 添加 id>0 是为了避免 条件1 不成立,条件 2 成立时 会出现 where or age > ?,查询语句出现错误。
2) <where> 用来包含 多个<if>的, 当多个if有一个成立的, <where>会自动增加一个where关键字,并去掉 if中多余的 and ,or等。
<!--
where: <where> <if> <if>...</where>
-->
<select id="selectStudentWhere" resultType="com.bjpowernode.domain.Student">
<include refid="studentSql" />
<where>
<if test="name !=null and name !='' ">
name = #{name}
</if>
<if test="age > 0">
or age > #{age}
</if>
</where>
</select>
注:这里不用担心 条件1 不成立 而 条件 2 成立的问题,因为 <where> 标签能把多余的标签比如 or and 去掉。
3) <foreach> 循环java中的数组,list集合的。 主要用在sql的in语句中。
学生id是 1001,1002,1003的三个学生select * from student where id in (1001,1002,1003)
public List<Student> selectFor(List<Integer> idlist)
List<Integer> list = new ...
list.add(1001);
list.add(1002);
list.add(1003);dao.selectFor(list)
<foreach collection="" item="" open="" close="" separator="">
#{xxx}
</foreach>collection:表示接口中的方法参数的类型, 如果是数组使用array , 如果是list集合使用list
item:自定义的,表示数组和集合成员的变量
open:循环开始是的字符
close:循环结束时的字符
separator:集合成员之间的分隔符
<!--foreach使用1 , List<Integer>-->
<select id="selectForeachOne" resultType="com.bjpowernode.domain.Student">
select * from student where id in
<foreach collection="list" item="myid" open="(" close=")" separator=",">
#{myid}
</foreach>
</select>