不积跬步,无以至千里;不积小流,无以成江海。

Mybatis学习之路—动态SQL查询

JAVA 康康 1338℃ 0评论

mybatis中 使用 动态SQL:if / where /when/otherwise/trim 等条件配合使用,实现强大的动态SQL

定义一个结果集

<resultMap type="Employee" id="empRes">

<id property="id" column="id" />

<result property="username" column="username" />

<result property="salary" column="salary" />

</resultMap>

parameterType="Map" 参数类型为Map

resultMap="empRes" 使用已经定义结果集

3

1. 使用 if 条件

<!-- 动态Sql if条件-->

<select id="searchEmp" parameterType="Map" resultMap="empRes">

select * from  employee where  deptID=#{deptID}

<!-- 动态查询 判断条件拼接 -->

<if test="username!=null">

and username like #{username}

</if>

<if test="salary!=null">

and salary=#{salary}

</if>
</select>

2. 使用 choose/when/otherwise

<!-- 动态SQL choose/when -->
<select id="searchEmpByType" parameterType="Map" resultMap="empRes" >

select * from employee

<choose>

<when test="searchBy=='deptID' ">

where deptID=#{deptID}

</when>

<when test="searchBy=='username' ">

where username like #{username}

</when>

<when test="searchBy=='salary' ">

where salary=#{salary}

</when>

</choose>
</select>

3. 使用 where/if 如果句子以and或or开头将自动删除 容错

<select id="searchEmp2" parameterType="Map" resultMap="empRes" >

select * from employee

<where>

<!-- where将自动添加或删除and -->

<if test="deptID!=null">

deptID=#{deptID}

</if>

<if test="username!=null">

and username like #{username}

</if>

<if test="salary!=null">

and salary=#{salary}

</if>

</where>
</select>

4. 使用trim条件 提供前后缀功能 更加灵活

<select id="searchEmp3" parameterType="Map" resultMap="empRes" >

select * from employee
<!--

prefix="where" :添加前缀where

prefixOverrides="and | or" 自动覆盖and | or

功能和上边where相同
-->
<trim prefix="where" prefixOverrides="and | or">

<if test="deptID!=null">

deptID=#{deptID}

</if>

<if test="username!=null">

and username like #{username}

</if>

<if test="salary!=null">

and salary=#{salary}

</if>
</trim>
</select>

 

5. foreach循环

<!-- 测试foreach条件
item="deptID" 遍历的取值
open="(" 开始加 (
separator="," 逗号分隔
close=")" 结束加 )
最终 实现 (2,3,4,5,6 )
-->
<select id="searchEmp4" parameterType="Map" resultMap="empRes" >

select * from employee

<where>

<if test="deptIds!=null">

deptID in

<foreach  collection="deptIds"  item="deptID"  open="(" separator="," close=")"  >

#{deptID}

</foreach>

</if>

</where>
</select>

 

6. set 条件(使用set使更新时不必再次更新全部数据)

<!--
set 有容错功能 自动剔除最后一个逗号,
-->
<update id="updateEmp" parameterType="Employee">

update employee

<set>

<if test="username!=null">

username=#{username},

</if>

<if test="salary>0">

salary=#{salary}

</if>

</set>

where id=#{id}
</update>

转载请注明:左手代码右手诗 » Mybatis学习之路—动态SQL查询

喜欢 (2)or分享 (0)
发表我的评论
取消评论

 

表情

Hi,您需要填写昵称和邮箱!

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址