在MyBatis在SQL映射文件中可以灵活、智能的动态SQL来实现SQL映射。
有以下方案:
1.if+set:完成更新操作
2.if+where:完成多条件查询
3.if+trim:完成多条件查询(替代where)或者更新操作(替代set)
4.foreach:完成复杂查询、主要用在in条件查询中,迭代集合。
5.choose:完成条件查询,好比Java中switch一样。
例子:在xml文件中 if+trim实现
<update id="ProviderUpdateById" parameterType="Provider">
update smbms_provider
<trim prefix="set" suffixOverrides="," suffix="where id =#{id}">
<if test="proCode != null">proCode=#{proCode},</if>
<if test="proName != null">proName=#{proName},</if>
<if test="proDesc != null">proDesc=#{proDesc},</if>
<if test="proContact != null">proContact=#{proContact},</if>
<if test="proPhone != null">proPhone=#{proPhone},</if>
<if test="proAddress != null">proAddress=#{proAddress},</if>
<if test="proFax != null">proFax=#{proFax},</if>
<if test="modifyDate != null">modifyDate=#{modifyDate},</if>
<if test="modifyBy != null">modifyBy=#{modifyBy},</if>
</trim>
</update>
例子2:在xml文件中 choose实现
<select id="getProviderList_choose" resultType="Provider">
select * from smbms_provider where 1=1
<choose>
<when test="proCode != null and proCode!= ''">
and proCode=#{proCode}
</when>
<when test="proName!=null and proName!= ''">
and proName=#{proName}
</when>
<when test="proContact != null and proContact!=''">
and proContact=#{proContact}
</when>
<otherwise>
and YEAR(creationDate) =YEAR(#{creationDate})
</otherwise>
</choose>
例子3:在xml文件中 foreach实现
<select id="getUserByRoleId_foreach_map" resultMap="userMapByRole">
select * from smbms_user where userRole in
<foreach collection="rKey" item="roleMap" open="(" separator="," close=")">
#{roleMap}
</foreach>
</select>
注意:此处foreach的collection为map集合的KEY值
MyBatis对sql操作非常强大。

967

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



