在MyBatis中,可以使用嵌套查詢(nested queries)或者聯合查詢(join queries)來返回多張表的字段。
例如:
<select id="getUserWithOrders" resultMap="UserWithOrdersResultMap">
select * from users
where user_id = #{userId}
</select>
<resultMap id="UserWithOrdersResultMap" type="User">
<result property="userId" column="user_id"/>
<result property="userName" column="user_name"/>
<collection property="orders" ofType="Order" resultMap="OrderResultMap"/>
</resultMap>
<resultMap id="OrderResultMap" type="Order">
<result property="orderId" column="order_id"/>
<result property="orderDate" column="order_date"/>
<result property="totalAmount" column="total_amount"/>
</resultMap>
例如:
<select id="getUserWithOrders" resultMap="UserWithOrdersResultMap">
select u.*, o.*
from users u
join orders o on u.user_id = o.user_id
where u.user_id = #{userId}
</select>
<resultMap id="UserWithOrdersResultMap" type="User">
<result property="userId" column="user_id"/>
<result property="userName" column="user_name"/>
<result property="orderId" column="order_id"/>
<result property="orderDate" column="order_date"/>
<result property="totalAmount" column="total_amount"/>
</resultMap>
通過以上方式,可以實現在MyBatis中返回多張表的字段。需要根據具體業務需求選擇合適的方法來查詢關聯的表數據。