在MyBatis中使用Collection映射復(fù)雜數(shù)據(jù)類型可以通過使用resultMap和association標(biāo)簽來實(shí)現(xiàn)。下面是一個(gè)示例:
假設(shè)有一個(gè)Order類和一個(gè)Product類,Order類中包含一個(gè)List類型的products屬性:
public class Order {
private int id;
private List<Product> products;
// getters and setters
}
public class Product {
private int id;
private String name;
// getters and setters
}
在MyBatis的映射文件中,可以通過resultMap來定義如何映射這兩個(gè)類之間的關(guān)系:
<resultMap id="orderResultMap" type="Order">
<id property="id" column="order_id"/>
<collection property="products" ofType="Product">
<id property="id" column="product_id"/>
<result property="name" column="product_name"/>
</collection>
</resultMap>
在查詢語句中使用這個(gè)resultMap來獲取Order對象及其關(guān)聯(lián)的Product對象:
<select id="getOrder" resultMap="orderResultMap">
SELECT o.id as order_id, p.id as product_id, p.name as product_name
FROM orders o
JOIN order_products op ON o.id = op.order_id
JOIN products p ON op.product_id = p.id
WHERE o.id = #{orderId}
</select>
這樣就可以在MyBatis中使用Collection映射復(fù)雜數(shù)據(jù)類型了。當(dāng)查詢結(jié)果中包含多個(gè)Product對象時(shí),這些Product對象會(huì)被映射到Order對象的products屬性中。