动态SQL :
动态SQL : SQL 语句的内容是变化的 , 我们可以根据条件获取到不同的sql语句 ,主要是where部分发 生变化
动态SQL的实现 : 使用的是mybatis提供的各种标签 ,
动态SQL要使用java对象作为参数 ,
if : 判断条件的
-
<!--语法 :--> <if test="判断java对象的属性值"> 部分SQL语句 </if>
-
<select id="selectStudentIf" resultType="org.sichen.domain.Student"> select id, name, email, age from student where 1 = 1 <if test="name!=null and name!=''"> and name = #{name} </if> <if test="age>0"> and age = #{age} </if> </select>
where:用来包含多个if的 ,
当多个if有一个成立的话 , where标签会自动增加一个where关键字 , 并去掉if中多余的and , or 等
(比如说 , 有些条件前边是or 直接加这个条件会造成SQL语法错误 , 但是where能够自动将这个or去掉 , 把语法错误避开)
如果都不满足 , 就什么都不会加 , 也不会加where语句
<select id="selectStudentWhere" resultType="org.sichen.domain.Student">
select id, name, email, age
from student
<where>
<if test="name!=null and name!=''">
and name = #{name}
</if>
<if test="age>0">
and age = #{age}
</if>
</where>
</select>
注意: 从上往下 , 第一个if中的条件可以不加 连接语句 , 但是后边的语句都要加连接语句 , 最好是全部加上
foreach: 循环java中的数组 或 list集合的
主要用在SQL的in语句中
学生id是 1001 , 1002 , 1003 的三个学生
select * from student where id in (1001 , 1002 , 1003);
<select id="selectStudentForeach" resultType="org.sichen.domain.Student">
select id,name,email,age
from student
where id in
<foreach collection="list" item="myid" open="(" close=")" separator=",">
#{myid}
</foreach>
</select>
<!--
collection : 表示接口中的方法参数的类型 , 如果是数组使用array , 如果是list集合使用list
item : 自定义的 , 表示数组和集合成员的变量
open : 循环开始时的字符 "("
close : 循环结束时的字符 ")"
separator : 集合成员之间的符号 ","
-->
如果传递的是一个List 里边存储的是一个Student对象 ,
<foreach collection="list" item="stu" open="(" close=")" separator=",">
#{stu.id}
</foreach>
动态SQL之代码片段 :
<!--定义 sql片段 , 使用的是sql 标签 id值与下边引用这个代码片段的refid的值一致-->
<sql id="studentSql">
select id,name,email,age from student
</sql>
<select id="selectStudentsql" resultType="org.sichen.domain.Student">
/*引用SQL片段的时候使用include标签 refid的值就是上边sql标签中的id值*/
<include refid="studentSql" />
<if test="list!=null and list.size>0">
where id in
<foreach collection="list" item="id" open="(" close=")" separator=",">
#{id}
</foreach>
</if>
</select>