在MyBatis中,可以通過在mapper文件中使用嵌套查詢(nested select)、嵌套結果映射(nested result mappings)或者嵌套選擇器(nested select with include)來實現關聯查詢。
<!-- 定義一個select語句 -->
<select id="getUserById" resultType="User">
SELECT * FROM user WHERE id = #{id}
</select>
<!-- 引用上面定義的select語句,實現關聯查詢 -->
<select id="getUserWithOrders" resultType="User">
SELECT * FROM user WHERE id = #{id};
<!-- 嵌套查詢 -->
<select id="getOrdersByUserId" resultType="Order">
SELECT * FROM orders WHERE user_id = #{id}
</select>
</select>
<resultMap id="UserResultMap" type="User">
<id property="id" column="id"/>
<result property="name" column="name"/>
<!-- 嵌套結果映射 -->
<collection property="orders" ofType="Order">
<id property="id" column="id"/>
<result property="name" column="name"/>
</collection>
</resultMap>
<resultMap id="UserResultMap" type="User">
<id property="id" column="id"/>
<result property="name" column="name"/>
<!-- 嵌套選擇器 -->
<collection property="orders" ofType="Order" select="getOrdersByUserId">
<id property="id" column="id"/>
<result property="name" column="name"/>
</collection>
</resultMap>
以上是幾種在MyBatis中實現關聯查詢的方法,開發人員可以根據具體的需求和情況選擇合適的方式來進行關聯查詢。