MyBatis 动态SQL详解

     MyBatis的优势

      MyBatis 的强大特性之一便是它的动态 SQL 能力。如果你有使用 JDBC 或其他类似框架的经验,你就能体会到根据不同条件拼接 SQL 字符串有多么痛苦。拼接的时候要确保不能忘了必要的空格,还要注意省掉列名列表最后的逗号。利用动态 SQL 这一特性可以彻底摆脱这种痛苦。

二、基本参数释义

1.Mapper.xml之insert

<!-- 查询的statement,id:在同一namespace下的唯一标识,resultType:结果集的包装类型 -->
<!--
    insert:表示需要插入的语句
    parameterType:调用insert方法传入的参数,对象的字段要和数据表中的字段相对应,对于八大基本数据类型java.lang.Long简写为long      
    keyColumn:数据库中自增长的字段名
    keyProperty:自增长中应注入实体类中的字段值
    useGeneratedKeys:标记这个标签需要使用数据库中的自增长id
--> 
<insert id="save" parameterType="User" keyColumn="id" keyProperty="id" useGeneratedKeys="true" >
    INSERT INTO tb_user (user_name,password,name,age,sex) VALUES (#{userName},#{password},#{name},#{age},#{sex})
</insert>

2.返回结果之Map

<!--对象中的字段和数据库中的字段相同--> 
<select id="getList" resultType="User" >
    SELECT id ,user_name , password ,age ,name  from tb_user
</select>
<!--
    对象中的字段和数据库中的字段不相同或者有别名的时候,我们用map来进行封装对象
    column:查询出来的字段
    property:对象中字段名
    type:返回的对象类型
-->
<resultMap id="basicMap" type="User">

    <id column="d_id" property="id" ></id>
    <result column="d_username" property="userName" ></result>
    <result column="d_password" property="password" ></result>
    <result column="d_age" property="age" ></result>
    <result column="d_name" property="name" ></result>
</resultMap>
<select id="getList1"  resultMap="basicMap" >
    SELECT id as d_id,user_name as d_username, password as  d_password,age as d_age,name as d_name from tb_user
</select>

三、动态SQL

  • IF
<!--动态 SQL 通常要做的事情是有条件地包含 where 子句的一部分,将会更加的灵活 -->
<select id="getObjectByCondition" parameterType="com.shenzhenair.mybatis.demo_01.QueryObject" resultType="User">
   SELECT  * FROM tb_user
   <where>
     <if test="keyword != null and keyword != '' ">
        AND user_name LIKE concat('%',#{keyword},'%')
     </if>
     <if test="beginAge != null">
         AND age <![CDATA[>=]]> #{beginAge}
     </if>
     <if test="endAge != null">
         AND age &lt;=  #{endAge}
     </if>
   </where>
</select>

 

  • choose (when, otherwise)
<!-- 
有些时候,我们不想用到所有的条件语句,而只想从中择其一二。针对这种情况,MyBatis 提供了 choose 元素,它有点像 Java 中的 switch 语句。-->
<select id="findActiveBlogLike"
     resultType="Blog">
  SELECT * FROM BLOG WHERE state = ‘ACTIVE’
  <choose>
    <when test="title != null">
      AND title like #{title}
    </when>
    <when test="author != null and author.name != null">
      AND author_name like #{author.name}
    </when>
    <otherwise>
      AND featured = 1
    </otherwise>
  </choose>
</select>

 

  • trim (where, set)
<!--
前面几个例子已经合宜地解决了一个臭名昭著的动态 SQL 问题。现在考虑回到“if”示例,这次我们将“ACTIVE = 1”也设置成动态的条件,看看会发生什么。
-->
<select id="findActiveBlogLike"
     resultType="Blog">
  SELECT * FROM BLOG 
  WHERE 
  <if test="state != null">
    state = #{state}
  </if> 
  <if test="title != null">
    AND title like #{title}
  </if>
  <if test="author != null and author.name != null">
    AND author_name like #{author.name}
  </if>
</select>
<!--
如果这些条件没有一个能匹配上将会怎样?最终这条 SQL 会变成这样:
-->
ELECT * FROM BLOG  WHERE 
<--where 元素知道只有在一个以上的if条件有值的情况下才去插入“WHERE”子句。而且,若最后的内容是“AND”或“OR”开头的,where 元素也知道如何将他们去除。-->
<select id="findActiveBlogLike"
     resultType="Blog">
  SELECT * FROM BLOG 
  <where> 
    <if test="state != null">
         state = #{state}
    </if> 
    <if test="title != null">
        AND title like #{title}
    </if>
    <if test="author != null and author.name != null">
        AND author_name like #{author.name}
    </if>
  </where>
</select>
<!--
   类似的用于动态更新语句的解决方案叫做 set。set 元素可以被用于动态包含需要更新的列,而舍去其他的。比如:
-->
<update id="updateAuthorIfNecessary">
  update Author
    <set>
      <if test="username != null">username=#{username},</if>
      <if test="password != null">password=#{password},</if>
      <if test="email != null">email=#{email},</if>
      <if test="bio != null">bio=#{bio}</if>
    </set>
  where id=#{id}
</update>
<!--
   如果 where 元素没有按正常套路出牌,我们还是可以通过自定义 trim 元素来定制我们想要的功能。比如,和 where 元素等价的自定义 trim元素
 --> 
<trim prefix="WHERE" prefixOverrides="AND |OR ">
  ... 
</trim>
<trim prefix="SET" suffixOverrides=",">
  ...
</trim>
<update id="updateObjectByCondition" parameterType="com.shenzhenair.mybatis.demo_01.QueryObject">
    UPDATE  tb_user
   <!-- <set>
        <if test="keyword != null and keyword != ''">
            user_name = #{keyword},
        </if>
        <if test="beginAge != null">
            age = #{beginAge},
        </if>

    </set>-->
    <trim prefix="set" suffixOverrides=",">
        <if test="keyword != null and keyword != ''">
            user_name = #{keyword},
        </if>
        <if test="beginAge != null">
            age = #{beginAge},
        </if>
    </trim>
    where id = #{id}
</update>
  •  foreach
<!--
     动态 SQL 的另外一个常用的必要操作是需要对一个集合进行遍历,通常是在构建 IN 条件语句的时候。
     foreach 元素是非常强大的,它允许你指定一个集合,声明可以用在元素体内的集合项和索引变量。它也允许你指定开闭匹配的字符串以及在迭代之间放置分隔符。这个元素是很智能的,因此它不会偶然地附加多余的分隔符。
     注意:你可以将一个 List 实例或者数组作为参数对象传给 MyBatis,当你这么做的时候,MyBatis 会自动将它包装在一个 Map 中并以名称为键。List 实例将会以“list”作为键,而数组实例的键将是“array”。
-->
<select id="getListByIds" parameterType="list" resultType="User">
    SELECT  * FROM  tb_user WHERE  id IN
    <foreach collection="list" item="id" open="(" close=")" separator=",">
        #{id}
    </foreach>
</select>
  • CommonSQL抽取
    
    <sql id="commonSql" >
        <where>
            <if test="keyword != null and keyword != '' ">
                AND user_name LIKE concat('%',#{keyword},'%')
            </if>
            <if test="beginAge != null">
                AND age <![CDATA[>=]]> #{beginAge}
            </if>
            <if test="endAge != null">
                AND age &lt;=  #{endAge}
            </if>
        </where>
    </sql>
    
    <select id="getCount" parameterType="com.shenzhenair.mybatis.demo_01.QueryObject" resultType="long">
        SELECT  count(*) FROM tb_user
      <include refid="commonSql"  ></include>
    
    </select>
    
    <select id="getPageResult" parameterType="com.shenzhenair.mybatis.demo_01.QueryObject" resultType="User">
        SELECT  * FROM tb_user
        <include refid="commonSql"  ></include>
        limit #{start}, #{row};
    </select>

 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值