mybatis 语法标签 【vaynexiao】

if

<select id="queryBlogIF" parameterType="map" resultType="com.rui.pojo.Blog">
    select * from mybatis.bolg where 1=1
    <if test="title != null">
        and title = #{title}
    </if>
    <if test="author != null">
        and author = #{author}
    </if>
</select>

choose (when, otherwise)

<select id="queryBlogChoose" parameterType="map" resultType="com.rui.pojo.Blog">
    select * from mybatis.bolg
    <where>
        <choose>
            <when test="title != null">
                title=#{title}
            </when>
            <when test="author!=null">
                and author = #{author}
            </when>
            <otherwise>
                and views = #{views}
            </otherwise>
        </choose>
    </where>
</select>

trim, (where, set)

select * from mybatis.bolg
<where>
<if test="title != null">
    title = #{title}
</if>
<if test="author != null">
    and author = #{author}
</if>
</where>
<update id="updateBlog" parameterType="map">
    update mybatis.bolg
    <set>  <!-- set会删除最后一个逗号 -->
        <if test="title != null">
            title = #{title},
        </if>
        <if test="author != null">
            author = #{author},
        </if>
    </set>
    where id = #{id}
</update>

sql include

<sql id="if-title-author">
    <if test="title != null">
        title = #{title}
    </if>
    <if test="author != null">
        and author = #{author}
    </if>
</sql>

<select id="queryBlogIF" parameterType="map" resultType="com.rui.pojo.Blog">
    select * from mybatis.bolg
    <where>
        <include refid="if-title-author"></include>
    </where>
</select>

foreach

查询id=1 or id=3 or id=5

select * from user where 1=1 and 
  <foreach item="id" index="index" collection="ids"
      open="(" separator="or" close=")">
        #{id}
  </foreach>
<!-- 表示从ids这个参数中取出id, 拼接成 (id=1 or id=2 or id=3)  -->

<!--  select * from mybatis.bolg where 1=1 and (id=1 or id=2 or id=3)
我们现在传递一个万能的map,这个map中可以存在一个map  -->
<select id="queryBlogForeach" parameterType="map" resultType="com.rui.pojo.Blog">
    select * from mybatis.bolg

    <where>
    <foreach collection="ids" item="id" open="(" close=")" separator="or">
        id = #{id}
    </foreach>
    </where>
</select>

再举一个例子

<update id="updateLxdh"  parameterType="java.util.HashMap">
          --这种方式是执行了多个update语句,上一种方式是一个语句;速度肯定是单个语句快
      <foreach collection="list/array/map" item="item" index="index" separator=";">
              update hr_user_base_info set lxdh =#{item.lxdh} where usercode =#{item.usercode}
      </foreach>
  </update>

trim

待整理

.trim() .toString()

select count(*) as sum_total_score from rz_applyer_officer_config
<where> 1=1
	<if test="year_id != null and year_id !='' ">
		and renzhu.year_id = #{year_id}
	</if>
	<if test="pcmc_name != null and deptName.trim() == '信息服务部'.toString() ">
		and p2.username like  '%${name}%'
	</if>
</where>
发布了75 篇原创文章 · 获赞 106 · 访问量 16万+

猜你喜欢

转载自blog.csdn.net/vayne_xiao/article/details/105318459