MyBatis的动态SQL
mybatis的强大特性之一就是动态SQL。我们在写复杂查询的时候,会发现复杂查询包括了各种各样的判断,我们很难一鼓作气的写出完美的查询。动态SQL语句可以帮助我们拼接不同的SQL语句,而已让我们的代码变得更加优雅且功能更加强大。
MyBatis的动态SQL在XML中支持的几种标签,他们分别是:
- if
- choose
- trim(where、set)
- foreach
- bind
if用法
if标签通常用于WHERE语句中,通过判断参数值来决定是否使用某个查询条件, 他也经常用于UPDATE语句中判断是否更新某一个字段,还可以在INSERT语句中用来判断是否插入某个字段的值
where:(我们的项目中模糊查询很多都用到了if,如果模糊条件不为空,则执行模糊查询,如果为空就到此为止)
<select id="FuzzyQueryClassByStrlike" parameterType="java.lang.String" resultType="com.dmsdbj.itoo.basicInfo.entity.ext.DivideClassModel">
select
tc.id as classId,
tc.class_code as classCode,
tc.class_name as className,
tc.profession_id as professionId,
p.major_name as professionName,
p.institution_id as InsititutionId,
i.institution_name as InsititutionName
from t_class tc
inner join t_profession p on tc.profession_id = p.id
inner join t_institution i on p.institution_id=i.id
<if test="strLike !='' and strLike !=null">
WHERE(
tc.class_code LIKE concat('%',#{strLike},'%')
OR
tc.class_name LIKE concat('%',#{strLike},'%')
OR
p.major_name LIKE concat('%',#{strLike},'%')
OR
i.institution_name LIKE concat('%',#{strLike},'%')
)
</if>
update(insert同理):如果要更新很多字段,但是一个步骤就可以完成,我们就可以使用if来进行判断,如果这个参数不为空则更新
<update id="updateById" parameterType="com.dmsdbj.itoo.basicInfo.entity.EducationExperienceEntity">
update t_education_experience
<set>
<if test="remark != null">
remark = #{remark,jdbcType=VARCHAR},
</if>
<if test="operator != null">
operator = #{operator,jdbcType=VARCHAR},
</if>
<if test="endDate != null">
end_date = #{endDate,jdbcType=DATE},
</if>
<if test="schoolName != null">
school_name = #{schoolName,jdbcType=VARCHAR},
</if>
<if test="startDate != null">
start_date = #{startDate,jdbcType=DATE},
</if>
<if test="teacherName != null">
teacher_name = #{teacherName,jdbcType=VARCHAR},
</if>
<if test="studentId != null">
student_id = #{studentId,jdbcType=VARCHAR},
</if>
<if test="isDelete != null">
is_delete = #{isDelete,jdbcType=TINYINT},
</if>
<if test="education != null">
education = #{education,jdbcType=VARCHAR},
</if>
<if test="createTime != null">
create_time = #{createTime,jdbcType=TIMESTAMP},
</if>
<if test="updateTime != null">
update_time = #{updateTime,jdbcType=TIMESTAMP},
</if>
</set>
where id = #{id,jdbcType=VARCHAR} and is_delete = 0
</update>
注意:
if标签中有一个test属性,test属性值是一个符合OGNL要求的判断表达式,表达式的结果可以使true或者false,除此之外所有的非0值都为true。