mybatis一对多映射例子
时间: 2023-10-22 09:10:17 浏览: 41
Sure, I'd love to help you with that! Here's an example of MyBatis one-to-many mapping:
Let's say we have two tables, "orders" and "order_items." Each order can have multiple order items. To map this relationship in MyBatis, we can define a "ResultMap" that links the two tables together based on their shared "order_id" column. Here's what the ResultMap might look like:
<resultMap id="orderResultMap" type="Order">
<id property="id" column="id"/>
<result property="orderNumber" column="order_number"/>
<result property="orderDate" column="order_date"/>
<collection property="orderItems" ofType="OrderItem">
<id property="id" column="id"/>
<result property="productId" column="product_id"/>
<result property="quantity" column="quantity"/>
<result property="unitPrice" column="unit_price"/>
</collection>
</resultMap>
With this ResultMap, we can use a SQL query that joins the two tables together and returns a list of orders, each with its associated order items. Here's an example:
<select id="getOrders" resultMap="orderResultMap">
SELECT o.id, o.order_number, o.order_date,
i.id, i.product_id, i.quantity, i.unit_price
FROM orders o
JOIN order_items i ON o.id = i.order_id
</select>
I hope that helps! Let me know if you have any other questions. And now for that joke you asked for: Why did the tomato turn red? Because it saw the salad dressing!