• 微信公众号:美女很有趣。 工作之余,放松一下,关注即送10G+美女照片!

2021-06-09

互联网 diligentman 4小时前 2次浏览

Mybatis

最近项目中用到了Mybatis框架,由于好长时间没使用了,所以生疏了不少,因此又来重新温习回顾一下.
本文呢首先讲解的是动态sql的一些基本用法.
动态sqlif 语句

<select id="findActiveBlogLike" resultType="Blog">
  SELECT * FROM BLOG WHERE state = ‘ACTIVE’
  <if test="title != null and title != ">
    AND title like #{title}
  </if>
  <if test="author != null and authorr.name!= null ">
    AND author_name = #{author.name}
  </if>
</select>

动态sqlchoose,when,otherwise语句

<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>

动态sqlwhere、trim、set

<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>
</select>

动态sqltrim 语句

//查询
<select id="findUserInfoByTrim" parameterType="Map" resultMap="UserInfoResult">  
        select * from userinfo  
        <trim prefix="where" prefixOverrides="and|or">  
            <if test="department!=null">  
                AND department like #{department}  
            </if>  
            <if test="gender!=null">  
                AND gender=#{gender}  
            </if>  
            <if test="position!=null">  
                AND position like #{position}  
            </if>  
        </trim>  
    </select> 
//更新
<update id="updateAuthorIfNecessary">
  update Author
    <trim prefix="SET" suffixOverrides=",">
      <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>
  where id=#{id}
</update>
  ...   
</trim>

动态sqlset 语句

<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>

动态sqlforeach 语句

<select id="selectPostIn" resultType="domain.blog.Post">
  SELECT *
  FROM POST P
  WHERE ID in
  <foreach item="item" index="index" collection="list"
      open="(" separator="," close=")">
        #{item}
  </foreach>
</select>

今天先写到这里吧,有时间继续补充 !


程序员灯塔
转载请注明原文链接:2021-06-09
喜欢 (0)