掌握mybatis中的动态sql会对程序员的开发带来很大的便利,如果不能很好的掌握,开发中会遇到各种坑(楼主走过很多坑)。
-if
-choose (when, otherwise)
-trim (where, set)
-foreach
if
废话不多说,对程序员来说,代码是最直接明了的。
<select id="select" parameterType="User" resultType="User">
select * from User u where 1 = 1
<if test="username!= null">
and username= #{uername}
</if>
<if test="password != null">
and password = #{password}
</if>
</select>
此处if的作用就是如果if 标签的条件满足了就会拼接上满足相应的条件的代码。例如,如果User中的username=”踏雪无痕”,password=”123456”,则整个查询的sql语句就变成了:
select * from User u where 1=1 and username="踏雪无痕" and password="123456"
如果uername 和password同时都为null,则sql语句为:
select * from User u where 1=1
此外, if 标签中也可以同时存在多个条件,例如:
<select id="select" parameterType="User" resultType="User">
select * from user u where 1 = 1
<if test="username!= null and password != null">
and username= #{uername}
and password=#{password}
</if>
</select>
choose
有的时候我们需要这样一种需求,例如,那上面的例子来说,我想查询某个用户,可以按照username查询,也可以按照alias,即不允许同时按两个条件查询,只能选择一个条件。此时的if就不好实现这样的功能了。choose 闪亮登场。
看例子:
<select id="select" parameterType="User" resultType="User">
select * from user where 1 = 1
<choose>
<when test="username != null">
and username = #{username }
</when>
<when test="alias!= null">
and alias= #{alias}
</when>
<otherwise>
</otherwise>
</choose>
</select>
<choose>
标签有点类型java中的switch语句,<when>
类似于case,<otherwise>
类似defualt。我们都知道switch语句中只能满足一个case,如果不满足case就会执行default,同样,sql语句中如只能匹配一个when标签,如果匹配了一个when标签,其余的所有情况都不会在去匹配,例如,如果传入参数uername=”踏雪无痕”,此时应该匹配上<when test="username != null">
,那么后边的<when test="alias!= null">
将不会再匹配(无论后面还有多少个when)。sql语句为:
select * from user where 1=1 and username="踏雪无痕"
如果所有的when 条件都没有匹配成功,那么将执行otherwise(此处不执行任何语句)。sql语句为:
select * from user where 1=1