当前位置: 首页 > 工具软件 > W-Script > 使用案例 >

Mybatis---sql、script标签

阎善
2023-12-01

一、sql标签

  • <sql>用来定义可重用的 SQL 代码片段
<sql id="userColumns"> ${alias}.id,${alias}.username,${alias}.password </sql>
  • SQL 片段的使用,include 标签引用refid属性设置为sql标签id
<select id="selectUsers" resultType="map">
  select
    <include refid="userColumns"><property name="alias" value="t1"/></include>,
    <include refid="userColumns"><property name="alias" value="t2"/></include>
  from some_table t1
    cross join some_table t2
</select>
  • 复杂引用sql片段,property 单纯是设置值,然后通过${}调用,实现多sql片段的引用
<sql id="sometable">
  ${prefix}Table
</sql>

<sql id="someinclude">
  from
    <include refid="${include_target}"/>
</sql>

<select id="select" resultType="map">
  select
    field1, field2, field3
  <include refid="someinclude">
    <property name="prefix" value="Some"/>
    <property name="include_target" value="sometable"/>
  </include>
</select>

二、script标签

要在带注解的映射器接口类中使用动态 SQL,可以使用 script 元素。

 @Update({"<script>",
      "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}",
      "</script>"})
    void updateAuthorValues(Author author);

通常,直接使用注解开发时,属性时必填的,而利用script标签,就可以自主可为空的情况了

 类似资料: