动态sql语句有如下标签:
if
choose (when, otherwise)
trim (where, set)
foreach
1.if元素的使用
示例如下:
<selectid="getOneUseIf"resultType="com.lazy.mybatis.bean.Employee">
select id,last_name lastName,email from employee
where
<iftest="id!=null">
id = #{id} and
</if><iftest="lastName!=null and lastName!=''">
last_name = #{lastName} and
</if><iftest="email!=null and email.trim()!=''">
email = #{email}
</if></select>
select id, last_name lastName, email from employee where id = ? and
where元素的主要用来解决上述问题,但是注意此时只能解决语句前端冗余的情况
<selectid="getOneUseIf"resultType="com.lazy.mybatis.bean.Employee">
select id,last_name lastName,email from employee
<where><iftest="id!=null">
id = #{id}
</if><iftest="lastName!=null and lastName!=''">
and last_name = #{lastName}
</if><iftest="email!=null and email.trim()!=''">
and email = #{email}
</if></where></select>
<selectid="getOneUseIf"resultType="com.lazy.mybatis.bean.Employee">
select id,last_name lastName,email from employee
<trimprefix="where"suffixOverrides="and"><iftest="id!=null">
id = #{id} and
</if><iftest="lastName!=null and lastName!=''">
last_name = #{lastName} and
</if><iftest="email!=null and email.trim()!=''">
email = #{email}
</if></trim></select>