MyBatis实现动态SQL
MyBatis 最强大的特性之一就是它的动态语句功能。如果您以前有使用JDBC或者类似框架的 经历,您就会明白把SQL语句条件连接在一起是多么的痛苦,要确保不能忘记空格或者不要在 columns列后面省略一个逗号等。动态语句能够完全解决掉这些痛苦。
尽管与动态SQL一起工作不是在开一个party,但是MyBatis确实能通过在任何映射SQL语句中 使用强大的动态SQL来改进这些状况。
if 元素
if元素条件判断,动态 SQL 最常做的事就是有条件地包括 where 子句。例如:
<select id=”findActiveBlogWithTitleLike” parameterType=”Blog” resultType=”Blog”>
SELECT * FROM BLOG WHERE state = ‘ACTIVE’
<if test=”title != null”>
AND title like #{title}
</if>
</select>
where元素
where元素知道插入“where”如果它包含的标签中有内容返回的话。此外,如果返回的内容 以“AND” 或者 “OR”开头,它会把“AND” 或者 “OR”去掉。
<select id="findStudentList" parameterType="hashmap" resultMap="studentInfo">
select * from t_student
<where>
<if test="name!=null">
and name=#{name}
</if>
<if test="age!=null">
and age=#{age}
</if>
</where>
</select>
choose元素
有时候我们不想应用所有的条件,而是想从多个选项中选择一个。与 java 中的 switch 语句 相似,MyBatis 提供了一个 choose 元素。
when元素
当when里面的条件成立时,执行when标签内的语句
<select id="findStudentList" parameterType="hashmap" resultMap="studentInfo">
select * from t_student
<where>
<choose>
<when test="name!=null">
and name=#{name}
</when>
<when test="age!=null">
and age=#{age}
</when>
</choose>
</where<

MyBatis的动态SQL功能强大,能有效解决条件拼接的痛点。本文介绍了if、where、choose、when、otherwise、trim、set、foreach、settings元素的用法,以及XML中的特殊字符处理。例如,where元素会在有内容时添加'where',trim元素可以自定义前缀和后缀移除,而foreach用于集合迭代,如in条件。
最低0.47元/天 解锁文章
294

被折叠的 条评论
为什么被折叠?



