在MyBatis中处理多表关联查询有多种方法,以下是其中一种常用的方法:
<select id="selectUserById" resultType="User">
select * from user where id=#{id}
</select>
<select id="selectOrdersByUserId" resultType="Order">
select * from orders where user_id=#{userId}
</select>
<select id="selectUserWithOrders" resultMap="UserWithOrdersResultMap">
select * from user where id=#{id}
<collection property="orders" column="id" select="selectOrdersByUserId"/>
</select>
<resultMap id="UserWithOrdersResultMap" type="User">
<result property="id" column="id"/>
<result property="name" column="name"/>
<collection property="orders" ofType="Order">
<id property="orderId" column="order_id"/>
<result property="orderName" column="order_name"/>
</collection>
</resultMap>
在以上示例中,先定义了两个基本的查询语句selectUserById和selectOrdersByUserId,然后通过selectUserWithOrders来实现多表关联查询,同时使用resultMap来映射返回结果。
<select id="selectUserWithOrders" resultMap="UserWithOrdersResultMap">
select u.id as userId, u.name as userName, o.id as orderId, o.name as orderName
from user u
join orders o on u.id = o.user_id
where u.id=#{id}
</select>
<resultMap id="UserWithOrdersResultMap" type="User">
<result property="id" column="userId"/>
<result property="name" column="userName"/>
<collection property="orders" ofType="Order">
<id property="orderId" column="orderId"/>
<result property="orderName" column="orderName"/>
</collection>
</resultMap>
在以上示例中,使用JOIN关键字将user表和orders表关联起来,通过resultMap来映射返回结果。
以上是两种常用的处理多表关联查询的方法,开发者可以根据具体情况选择合适的方式来实现多表关联查询。