mybatis的动态SQL
1. MyBatis 的动态 SQL 元素与 JSTL 或 XML 文本处理器相似,常用1. <if>、
2. <choose>、<when>、<otherwise>、(if-else)
3. <trim>、<where>、<set>、
4. <foreach>
重点掌握标签:<if>/<where>/<foreach>/<trim>
1.if标签:
作用:可以根据自己传递的条件进行多条件查询
属性:
test:判断的条件,一般判断该值是否不为空
案例:
<select id="findStu" resultMap="studentMap" parameterType="student">
SELECT * FROM student WHERE 1=1
<if test="sex != null">
and sex = #{sex}
</if>
<if test="name != null">
and name=#{name}
</if>
/*模糊查询方式一*/
<if test="stunum != null">
and stunum like #{stunum}
</if>
/*模糊查询方式二*/
<if test="stunum != null">
and stunum like concat("%",#{stunum},"%")
</if>
/*模糊查询方式三*/
<if test="stunum != null">
and stunum like "%"#{stunum}"%"
</if>
</select>
2.where标签:
作用:替换where条件的恒等式 1=1
用法:
将if标签写在where标签中即可
案例:
<select id="findStu" resultMap="studentMap" parameterType="student">
SELECT * FROM student
<where>
<if test="sex != null">
and sex = #{sex}
</if>
<if test="name != null">
and name=#{name}
</if>
<if test="stunum != null">
and stunum like "%"#{stunum}"%"
</if>