在MyBatis中,可以通过使用<collection>
标签来实现集合的关联查询。以下是一个示例:
在Mapper XML文件中定义关联查询:
<!-- 查询订单及其订单项 -->
<select id="getOrderWithItems" resultMap="orderWithItems" parameterType="int">
SELECT * FROM orders WHERE id = #{id}
</select>
<resultMap id="orderWithItems" type="Order">
<id property="id" column="id"/>
<result property="orderNumber" column="order_number"/>
<collection property="orderItems" ofType="OrderItem" column="order_id" select="getOrderItemsByOrderId"/>
</resultMap>
<select id="getOrderItemsByOrderId" resultMap="orderItemResultMap" parameterType="int">
SELECT * FROM order_items WHERE order_id = #{id}
</select>
<resultMap id="orderItemResultMap" type="OrderItem">
<id property="id" column="id"/>
<result property="name" column="name"/>
<result property="quantity" column="quantity"/>
</resultMap>
在Java代码中调用关联查询:
public Order getOrderWithItems(int orderId) {
try(SqlSession sqlSession = sqlSessionFactory.openSession()) {
OrderMapper orderMapper = sqlSession.getMapper(OrderMapper.class);
return orderMapper.getOrderWithItems(orderId);
}
}
以上示例中,Order
类包含了一个List<OrderItem>
类型的属性orderItems
,通过在<resultMap>
中使用<collection>
标签来关联查询OrderItem
对象并映射到orderItems
属性中。在查询订单时,同时查询订单项,并将订单项关联到订单对象中。