如何通過MyBatis實(shí)現(xiàn)集合的關(guān)聯(lián)查詢

小樊
93
2024-08-08 09:35:43

在MyBatis中,可以通過使用<collection>標(biāo)簽來(lái)實(shí)現(xiàn)集合的關(guān)聯(lián)查詢。以下是一個(gè)示例:

在Mapper XML文件中定義關(guān)聯(lián)查詢:

<!-- 查詢訂單及其訂單項(xiàng) -->
<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代碼中調(diào)用關(guān)聯(lián)查詢:

public Order getOrderWithItems(int orderId) {
    try(SqlSession sqlSession = sqlSessionFactory.openSession()) {
        OrderMapper orderMapper = sqlSession.getMapper(OrderMapper.class);
        return orderMapper.getOrderWithItems(orderId);
    }
}

以上示例中,Order類包含了一個(gè)List<OrderItem>類型的屬性orderItems,通過在<resultMap>中使用<collection>標(biāo)簽來(lái)關(guān)聯(lián)查詢OrderItem對(duì)象并映射到orderItems屬性中。在查詢訂單時(shí),同時(shí)查詢訂單項(xiàng),并將訂單項(xiàng)關(guān)聯(lián)到訂單對(duì)象中。

0