标签
Mybatis通过if,choose,where,foreach,trim元素提供了对构造动态sql语句的高级别支持
详细使用
if条件
if元素被用来有条件的嵌入sql片段,如果测试条件为true,则相应的sql片段将会被添加到ssql语句中
示例
假定我们有一个课程搜索页,设置了讲师,课程名称,开始时间和结束时间作为搜索条件,假定讲师是必选的,其他都是可选的
当用户点击 搜索 按钮时,我们需要显示符合以下条件的课程表
- 特定讲师的课程
- 课程名
- 开始时间 和 结束时间
<resultMap id="CourseResult" type="Course">
<id property="courseId" column="course_id"/>
<result property="name" column="name"/>
<result property="description" column="description"/>
<result property="startDate" column="start_Date"/>
<result property="endDate" column="end_Date"/>
</resultMap>
<select id="searchCourses" parameterType="hashmap" resultMap="CourseResult">
select * from Courses
where tutpt_id = #{tutorId}
<if test="courseName != null">
and name like #{courseName}
</if>
<if test="startDate != null">
and start_date >= #{startDate}
</if>
<if test="endDate != null">
and end_date <= #{endDate}
</if>
</select>
此处将生成查询语句 SELECT * FROM COURSES WHERE TUTOR_ID= ? AND NAME like ? AND START_DATE >= ?
准备根据给定条件的动态 SQL 查询将会派上用场
choose,when,otherwise条件
若用户需要选择是否希望通过选择 讲师 课程名称 开始时间 结束时间来作为查询条件类别来进行查询,然后根据选择的查询类别,输入相应的参数,在这样的场景中,我们需要只使用其中一种查询类别
<select id="searchCourses" parameterType="hashmap" resultMap="CourseResult">
select * from courses
<choose>
<when test="searchBy == 'Tutor'">
where tutor_id = #{tutorId}
</when>
<when test="searchBy == 'CourseName'">
where name like #{courseName}
</when>
<otherwise>
where tutor start_date >= now()
</otherwise>
</choose>
</select>
choose使用第一个值为true的子句,如果没有条件为true,则使用otherwise内的子句
where条件
有时候,所有的查询条件应该是可选的,在需要使用至少一种查询条件的情况下,我们应该使用where子句,并且如果有多个条件,我们需要在条件中添加and或者or
<select id="searchCourses" parameterType="hashmap" resultMap="CourseResult">
select * from Courses
<where>
<if test="tutorId != null">
tutor_id=#{tutorId}
</if>
<if test="courseName != null">
and name like #{courseName}
</if>
</where>
</select>
where元素只有在其内部标签返回内容时才会在动态语句上插入where条件语句,并且如果where子句以and或者or打头,则打头的and/or将会被移除
trim条件
trim元素与where元素类似,但是trim提供了在添加前缀/后缀 或者 删除前缀/后缀方面更加具有灵活性
<select id="searchCourses" parameterType="hashmap"
resultMap="CourseResult">
select * from courses
<trim prefix="where" prefixOverrides="AND/OR">
<if test="tutorId != null">
tutor_id = #{tutorId}
</if>
<if test="courseName != null">
and name like #{courseName}
</if>
</trim>
</select>
这里如果任意一个if条件成立,trim元素会插入where,并且移除紧跟where后面的and或者or
foreach循环
<select id="searchCourse" parameterType="map" resultMap="CourseResult">
select * from courses
<if test="tutorIds != null">
<where>
<foreach item="tutorId" collection="tutorIds">
OR tutor_id = #{tutorId}
</foreach>
</where>
</if>
</select>
如果where子句以and或者or打头,则打头的and/or将会被移除
set条件
元素和元素类似,如果其内部条件判断有任何内容返回时,他会插入 SET SQL 片段
<update id="updateStudent" parameterType="Student">
update students
<set>
<if test="name != null">name = #{name},</if>
<if test="eamil!= nul">email=#{email}</if>
</set>
where stu_id = #{id}
</update>