在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
屬性中。在查詢訂單時,同時查詢訂單項,并將訂單項關聯到訂單對象中。