四.动态SQL
动态sql: sql的内容是变化的,可以根据条件获取到不同的sql语句. 主要是 where 部分发生变化
动态sql的实现, 使用的是mybatis提供的标签 , <if> <where> <foreach>
1.if 标签
1.<if>标签
<if>是判断条件的,
语法 <if test="判断java对象的属性值">
部分sql语句
</if>
<!-- if
<if test="使用参数java对象的属性值作为判断条件 , 语法 : 属性值==XXX值等等">
</if>
可能出现语法错误(多余的or或and)
-->
<select id="selectUserIf01" resultType="com.dsm.pojo.User">
select * from user where
<if test="id > 3">
id =
</if>
<if test="name !=null and name != ''">
and name =
</if>
</select>
2.where标签
<where> 用来包含 多个<if>的, 当多个if有一个成立, <where>会自动增加一个where关键字, 并去掉 if 多余的and , or等
<!-- where:
<where> <if><if>...</where>
内部有if成立才会自动在sql语句中加上一个where
去掉多余的or and等等(避免出现语法错误)
-->
<select id="selectUserWhere" resultType="com.dsm.pojo.User">
select * from user
<where>
<if test="id > 3">
id =
</if>
<if test="name !=null and name != ''">
and name =
</if>
</where>
</select>
3.foreach标签
<foreach> 用于循环java中的数组,list集合的. 主要用在sql的in语句中.
例如:查id为 1, 2, 3的
select * from user where id in (1,2,3)
现在1,2,3放在了数组或集合中使用<foreach>遍历到sql语句中
<foreach collection="" item="" open="" close="" separator="">
</foreach>
collection : 表示接口中的方法参数的类型,数组(array),List集合(list)
item : 自定义成员变量
open : 循环开始时的字符
close : 循环结束时的字符
separator : 集合成员之间的分隔符
<!--
foreach用法一(集合里面是数值)
-->
<select id="selectUserForeach01" resultType="com.dsm.pojo.User">
select * from user where id in
<foreach collection="list" item="listId" open="(" close=")" separator=",">
</foreach>
</select>
<!-- foreach用法二(集合里面是对象) -->
<select id="selectUserForeach02" resultType="com.dsm.pojo.User">
select * from user where id in
<foreach collection="list" item="user" open="(" close=")" separator=",">
</foreach>
</select>
4.代码片段(实现代码复用)
1.先使用
<sql id="自定义名称(唯一)">
sql语句, 表名, 字段名等
</sql>
2.在使用(插入sql语句的片段)
<include refid="id的值"/>