MyBatis 动态拼接Sql字符串的问题
MyBatis的一个强大的特性之一通常是它的动态SQL能力。如果你有使用JDBC或其他相似框架的经验,你就明白条件地串联SQL字符串在一起是多么的痛苦,确保不能忘了空格或在列表的最后省略逗号。动态SQL可以彻底处理这种痛苦。
动态SQL
MyBatis的动态SQL,解决了SQL字符串拼接的痛苦。
1.if
<selectid="findActiveBlogWithTitleLike" parameterType="Blog"resultType="Blog"> SELECT*FROMBLOG WHEREstate='ACTIVE' <iftest="title!=null"> ANDtitlelike#{title} </if> </select>
这条一句会提供一个可选的文本查找功能。如果没有传递title,那么所有激活的博客都会被返回。
如果传递了title,那么就会查找相近的title。
2.choose,when,otherwise
<selectid="findActiveBlogLike" parameterType="BLOG"resultType="BLOG"> SELECT*FROMBLOG WHERE <choose> <whentest="title!=null"> ANDtitlelike#{title} </when> <whentest="author!=nullandauthor.name!=null"> ANDtitlelike#{author.name} </when> <otherwise> ANDfeatured=1 </otherwise> </choose> </select>
注:如果上述条件都没有匹配,则会变成SELECT*FROMBLOGWHERE
如果仅有第二个匹配,则会变成SELECT*FROMBLOGWHEREANDtitleLIKEsomelike
显然这样会查询失败。要解决这个问题,mybatis提供了解决方法。
<selectid="findActiveBlogLike" parameterType="BLOG"resultType="BLOG"> SELECT*FROMBLOG WHERE <trimprefix="WHERE"prefixOverrides="AND|OR"> <choose> <whentest="title!=null"> ANDtitlelike#{title} </when> <whentest="author!=nullandauthor.name!=null"> ANDtitlelike#{author.name} </when> <otherwise> ANDfeatured=1 </otherwise> </choose> </trim> </select>
overrides属性采用管道文本分隔符来覆盖,这里的空白是重要的。它的结果就是移除在InnerText中overrides中指定的内容。
3.set
<updateid="updateAuthorIfNecessary" parameterType="Author"> updateAuthor <set> <iftest="username!=null">username=#{username},</if> <iftest="password!=null">password=#{password},</if> <iftest="email!=null">email=#{email}</if> </set> whereid=#{id} </update>
同上的问题,优化后:
<updateid="updateAuthorIfNecessary" parameterType="Author"> updateAuthor <trimprefix="where"prefixOverrides=","> <set> <iftest="username!=null">username=#{username},</if> <iftest="password!=null">password=#{password},</if> <iftest="email!=null">email=#{email}</if> </set> whereid=#{id} </trim> </update>
以上所述是小编给大家介绍的MyBatis动态拼接Sql字符串的问题,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对毛票票网站的支持!