动态SQL:根据不同条件拼接SQL语句,实现对数据库更精准的操作
语法:< if test =”条件”> 满足条件的语句 if>
注意:拼接 SQL 语句的时候注意 AND 和逗号
and可以在where后面加一个(1=1)来消除
<select id="findStudent" parameterType="Student" resultType="Student">
select * from student where 1=1
<if test="ssex != null">
and ssex = #{ssex}
</if>
<if test="classid != 0">
and classid = #{classid}
</if>
</select>
where就是用来代替sql语句中的where
<select id="findStudentwhere" parameterType="Student" resultType="Student">
select * from student
<where>
<if test="ssex != null">
and ssex = #{ssex}
</if>
<if test="classid != 0">
and classid = #{classid}
</if>
</where>
</select>
语法格式:
<choose>
<when test=“条件”>满足条件的语句</ when>
<otherwise> 满足其他条件的语句 <otherwise>
</choose>
类似于java中的Switch语句
<select id="findStudentChoose" parameterType="Student" resultType="Student">
select * from student
<where>
<choose>
<when test="sid != 0"> and sid = #{sid} </when>
<when test="sname != null"> and sname = #{sname} </when>
<when test="birthday != null"> and birthday = #{birthday} </when>
<when test="ssex != null"> and ssex = #{ssex} </when>
<when test="classid != 0"> and classid = #{classid} </when>
<otherwise>sid = (select max(sid) from student)</otherwise>
</choose>
</where>
</select>
prefix : 之前添加一个什么
prefixOverrides : 之前面后去掉一个什么
suffix : 之后添加一个什么
suffixOverrides : 之后去掉一个什么
语法格式:
<trim prefix = “”suffixOverrides = “” prefixOverrides=“”suffix=“”></trim>
案例:
<select id="findStudentTrim" parameterType="Student" resultType="Student">
select * from student
<trim prefix="where" prefixOverrides="and" >
<if test="ssex != null"> and ssex = #{ssex}</if>
<if test="classid != 0"> and classid = #{classid}</if>
</trim>
</select>
set就是代替了SQL语句中的set
set 标签元素主要是用在更新操作的时候,它的主要功能和 where 标签元素其实是差不多的,主要是在包含的语句前输出一个 set,然后如果包含的语句是以逗号结束的话将会把该逗号忽略,如果 set 包含的内容为空的话则会出错。有了 set 元素就可以动态的更新那些修改了的字段。
案例:
<update id="updateStudentset" 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>
标签中的属性:
参数是数组:
<select id="findStudentBySidArray" resultType="Student" >
select * from student
<where>
<foreach collection="array" item="x" open=" sid in (" close=")" separator=",">
#{x}
</foreach>
</where>
</select>
参数是集合:
<select id="findStudentBySidList" resultType="Student" >
select * from student
<where>
<foreach collection="list" item="x" open=" sid in (" close=")" separator=",">
#{x}
</foreach>
</where>
</select>
方式一:在test测试中改变输入参数“%李%”
方式二:使用concat()函数将多个字符串连接起来
select * from student where sname like concat("%",#{v},"%")
方式三:使用${} 字符串的替换
select * from student where sname like "%${v}%"
方式四:使用#{} 占位符
select * from student where sname like "%"#{v}"%"
方式五:使用bind标签
<bind name="snameValue" value="'%'+_parameter+'%'"/>
select * from student where sname like #{snameValue}