mybatis的动态标签

if

if选择标签
<if test=""></if>

where set trim


where自动去除前面多余的and or

select *
from order_details
        <where>
            <if test="id != null">
                and id = #{id}
            </if>
            <if test="orderId != null">
                and order_id = #{orderId}
            </if>
	</where>

trim和where差不多,但是功能更加强大

这样就和<where>一样,`prefixOverrides`表示去掉多余的前缀`and`
<trim prefix="where" prefixOverrides="and" suffix="" suffixOverrides="">
      <if test="id != null">
           and id = #{id}
     </if> ....
</trim>

set 搭配update标签使用

<update id="updateAuthorIfNecessary">
  update Author
  #这里的set可以自动添加set 并且消除多余的逗号
    <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>

也可以使用trim代替

<trim prefix="SET" suffixOverrides=",">
  ...
</trim>

choose when otherwise

choose when otherwise这三个需要一起使用,类似java的swtich
choose表示开启一个选择
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>

foreach


foreach用来遍历一个集合,自动拼接集合的内容

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

bind

bind用于给变量运算,并且保存中间结果

<select id="selectBlogsLike" resultType="Blog">
  <bind name="pattern" value="'%' + _parameter.getTitle() + '%'" />
  SELECT * FROM BLOG
  WHERE title LIKE #{pattern}
</select>

sql include


这个不算动态标签,但是比较常用
sql include 这两个也是一起使用的,sql定义一个已经写好的片段,include表示引用之前的sql

  <sql id="selectColumn">id,orderId,productId</sql>
    <select id="getxxx" resultMap="OrderDetailsMap">
        select *
        <include refid="selectColumn"/>
        from order_details;
    </select>
posted @ 2023-10-23 16:05  xiuer211  阅读(8)  评论(0编辑  收藏  举报