1. <select> 標(biāo)簽

<select> 標(biāo)簽是 MyBatis 中最常用的標(biāo)簽之一,用于定義查詢(xún)語(yǔ)句。它支持各種復(fù)雜的查詢(xún)條件,如參數(shù)綁定、動(dòng)態(tài) SQL、結(jié)果映射等。我們可以通過(guò) id 屬性為查詢(xún)語(yǔ)句命名,并在 Java 代碼中通過(guò)映射接口方法調(diào)用。例如:

<select id="getUserById" parameterType="int" resultType="com.example.User">
    SELECT * FROM users WHERE id = #{id}
</select>

2. <insert>、<update>和<delete>標(biāo)簽

除了 <select> 標(biāo)簽,MyBatis 還提供了 <insert>、<update> 和 <delete> 標(biāo)簽,分別用于定義添加、更新和刪除操作的 SQL 語(yǔ)句。與 <select> 標(biāo)簽類(lèi)似,我們同樣可以為這些語(yǔ)句命名并在 Java 代碼中調(diào)用。例如:

<insert id="createUser" parameterType="com.example.User">
    INSERT INTO users (name, email) VALUES (#{name}, #{email})
</insert>

3. 動(dòng)態(tài) SQL 標(biāo)簽

MyBatis 提供了一系列動(dòng)態(tài) SQL 標(biāo)簽,用于根據(jù)不同的條件動(dòng)態(tài)生成 SQL 語(yǔ)句。這些標(biāo)簽包括 <if>、<choose>、<when>、<otherwise>、<foreach> 和 <set>。通過(guò)這些標(biāo)簽,我們可以編寫(xiě)出非常靈活的 SQL 語(yǔ)句,滿足各種復(fù)雜的查詢(xún)需求。例如:

<select id="findActiveBlogWithTitleLike"
     parameterType="com.example.Blog" resultType="com.example.Blog">
  SELECT * FROM blog WHERE state = 'ACTIVE'
  <if test="title != null">
    AND title like #{title}
  </if>
</select>

4. 結(jié)果映射標(biāo)簽

MyBatis 提供了 <resultMap> 標(biāo)簽,用于定義復(fù)雜的結(jié)果集映射關(guān)系。通過(guò)它,我們可以將查詢(xún)結(jié)果映射到自定義的 Java 對(duì)象上,而不僅僅是簡(jiǎn)單的字段映射。<resultMap> 標(biāo)簽支持多表關(guān)聯(lián)查詢(xún),以及嵌套結(jié)果集的映射。例如:

<resultMap id="userResultMap" type="com.example.User">
  <id property="id" column="user_id" />
  <result property="username" column="user_name"/>
  <result property="password" column="hashed_password"/>
  <association property="address" javaType="com.example.Address">
    <id property="id" column="address_id"/>
    <result property="street" column="street"/>
    <result property="city" column="city"/>
    <result property="state" column="state"/>
  </association>
</resultMap>

5. SQL 片段標(biāo)簽

MyBatis 還提供了 <sql> 標(biāo)簽,用于定義可重用的 SQL 片段。我們可以在其他 SQL 標(biāo)簽中引用這些片段,以提高 SQL 的可維護(hù)性和復(fù)用性。例如:

<sql id="userColumns">
  id, username, password
</sql>

<select id="selectUsers" parameterType="int" resultType="hashmap">
  SELECT <include refid="userColumns"/>
  FROM users
  WHERE id = #{id}
</select>

6. 其他標(biāo)簽

除了上述主要的 SQL 標(biāo)簽,MyBatis 還提供了一些其他輔助性的標(biāo)簽,如 <include>、<trim>、<where>、<bind> 等,用于更靈活地編寫(xiě) SQL 語(yǔ)句。這些標(biāo)簽可以幫助我們進(jìn)一步優(yōu)化和簡(jiǎn)化 SQL 代碼,提高可讀性和可維護(hù)性。

總結(jié)本文全面介紹了 MyBatis 提供的各種 SQL 標(biāo)簽及其用法,包括查詢(xún)、添加、更新和刪除操作,以及動(dòng)態(tài) SQL、結(jié)果映射和 SQL 片段等高級(jí)功能。通過(guò)學(xué)習(xí)和理解這些標(biāo)簽,相信讀者能夠更好地掌握 MyBatis 的強(qiáng)大 SQL 編寫(xiě)能力,并在實(shí)際項(xiàng)目中發(fā)揮其最大效用。