什么叫动态SQL
如果嵌入的SQL没有明确给出,如在Java中定义了一个字符串类型的变量sql:String sql;,然后采用preparedStatement对象的execute方法去执行这个sql,该sql的值可能等于从文本框中读取的一个SQL或者从键盘输入的SQL,但具体是什么,在编译时无法确定,只有等到程序运行起来,在执行的过程中才能确定,这种SQL叫做动态SQL。
下面我将介绍编写动态aql语句时候经常用到的标签及实例
<if>标签 执行条件判断,成立则拼接,不成立则忽略
<select id="findStudentif" parameterType="Student" resultType="Student">
<include refid="stusql"></include>
where 1=1
<if test="ssex != null">
and ssex=#{ssex}
</if>
<if test="classid != 0">
and classid = #{classid}
</if>
<choose>标签 满足条件的语句
<otherwise>满足其他条件的语句
<select id="findStudentChoose" parameterType="Student" resultType="Student" >
<include refid="stusql"></include> where 1=1
<choose>
<when test="classid!=0"> classid = #{classid}</when>
<when test="sname!=null"> sname = #{sname}</when>
<otherwise>and sid=21</otherwise>
</choose>
<where>标签
where 元素只会在至少有一个子元素的条件返回 SQL 子句的情况下才去插入
<select id="findStudentWhere" parameterType="Student"
resultType="Student">
<include refid="stusql"></include>
<!-- 1.没有任何条件的时候,where整体不出现 2. 3. -->
<where>
<if test="ssex != null">
and ssex=#{ssex}
</if>
<if test="classid != 0">
and classid = #{classid}
</if>
</where>
</select>
<set>标签
set 标签元素主要是用在更新操作的时候,它的主要功能和 where 标签元素其实是差不多的,主是在包含的语句前输出一个 set,然后如果包含的语句是以逗号结束的话将会 把该逗号忽略,如果 set 包含的内容为空的 话则会出错。有了 set 元素就可以动态的更新那些修改了的字段
<update id="updateStudent" parameterType="student">
update student
<set>
<if test="sname!=null">
sname = #{sname},
</if>
<if test="birthday!=null">
birthday = #{birthday},
</if>
<if test="ssex!=null">
ssex = #{ssex},
</if>
<if test="classid!=0">
classid = #{classid},
</if>
</set>
<where>sid = #{sid}</where>
</update>
<trim>标签
<!-- trim 万能标签 preix 开头 suffix结尾 能代替where标签 set标签 -->
<update id="updateStudentBysid" parameterType="student">
update student
<trim prefix="set" suffixOverrides=",">
<if test="sname!=null">
sname = #{sname},
</if>
<if test="birthday!=null">
birthday = #{birthday},
</if>
<if test="ssex!=null">
ssex = #{ssex},
</if>
<if test="classid!=0">
classid = #{classid},
</if>
</trim>
<where>sid=#{sid}</where>
</update>
<foreach>标签
<select id="findStudentArray" resultType="student">
select * from student where sid in
<foreach collection="array" item="s" open="(" separator=","
close=")">
#{s}
</foreach>
</select>
以上结束↑