常用的动态sql使用

一、sql片段

组装sql我们不得不提到sql片段。就是我们可以把共有的一些sql语句抽离出来,组成sql片段。其他的statement就可以对其进行引用。

定义sql片段:

 
  1. <sql id="query_user_where">

  2. <if test="userCustom!=null">

  3. <if test="userCustom.sex!=null and userCustom.sex!=''">

  4. and user.sex=#{userCustom.sex}

  5. </if>

  6.  
  7. </if>

  8. </sql>

    扫描二维码关注公众号,回复: 3412715 查看本文章
  9.  

引用sql片段,只需引用sql片段的id名称即可:

 
  1. <!-- 用户信息综合查询 -->

  2. <select id="findUserList" parameterType="cn.itcast.mybatis.po.UserQueryVo" resultType="cn.itcast.mybatis.po.UserCustom">

  3. select * from user

  4. <where>

  5. <include refid="query_user_where"></include>

  6. </where>

  7.  
  8. </select>


二、动态SQL元素

1.if 

 
  1. <select id="findUserById" resultType="user">

  2. select * from user where

  3. <if test="id != null">

  4. id=#{id}

  5. </if>

  6. and isDelete=0;

  7. </select>

这个是有问题的,如果id为null,那么sql语句就成了“select * from userwhere and isDelete = 0”
所以就有了where这个元素

2.where

 
  1. <select id="findUserById" resultType="user">

  2. select * from user

  3. <where>

  4. <if test="id != null">

  5. id=#{id}

  6. </if>

  7. and isDelete=0;

  8. </where>

  9. </select>

3.foreach

当我们查询条件为数组或者List时,我们用foreach解析。比如传入多个用户id查询用户信息

(1)传入List

 
  1. <select id="selectUserByList" parameterType="java.util.List" resultType="user">

  2. select * from user

  3. <where>

  4. <!-- 传递List -->

  5. <if test="list!=null">

  6. <foreach collection="list" item="item" open="and id in("separator=","close=")">

  7. #{item.id}

  8. </foreach>

  9. </if>

  10. </where>

  11. </select>

  12.  

item:为数组每个元素的名称,名称随意定义
open:循环开始
close:循环结束
separator:中间分隔输出

(2)传入数组

 
  1. <select id="selectUserByArray" parameterType="Object[]" resultType="user">

  2. select * from user

  3. <where>

  4. <!-- 传递数组 -->

  5. <if test="array!=null">

  6. <foreach collection="array" index="index" item="item" open="and id in("separator=","close=")">

  7. #{item.id}

  8. </foreach>

  9. </if>

  10. </where>

  11. </select>

  12.  

index:为数组下标

4.set

 
  1. <update id="updateUser" parameterType="com.dy.entity.User">

  2. update user set

  3. <if test="username != null">

  4. name = #{username},

  5. </if>

  6. <if test="password != null">

  7. password = #{password},

  8. </if>

  9. <if test="age != null">

  10. age = #{age}

  11. </if>

  12. <where>

  13. <if test="id != null">

  14. id = #{id}

  15. </if>

  16. and isDelete = 0;

  17. </where>

  18. </update>


这几个是比较常用的,还有跟switch相似的choose和otherwise,还有trim,这里就不一一介绍了。大家有兴趣可以了解一下。

猜你喜欢

转载自blog.csdn.net/LRXmrlirixing/article/details/82746717
今日推荐