举一个Ibatis中collection使用的例子
时间: 2024-05-05 16:18:01 浏览: 14
好的,举一个Ibatis中collection使用的例子。假设我们有两个表:订单表和订单明细表。每个订单可能有多个订单明细。现在我们希望通过Ibatis实现查询一个订单及其所有订单明细的功能。这时候可以使用Ibatis中的collection来实现。具体地,在订单的映射文件中,可以使用如下SQL语句和resultMap来获取订单及其所有订单明细:
```
<select id="getOrderWithDetails" parameterType="int" resultMap="orderResultMap">
select *
from orders o
left join order_details od on o.order_id = od.order_id
where o.order_id = #{orderId}
</select>
<resultMap id="orderResultMap" type="Order">
<id property="id" column="order_id"/>
<result property="orderNo" column="order_no"/>
<collection property="details" ofType="OrderDetail">
<id property="id" column="detail_id"/>
<result property="name" column="detail_name"/>
</collection>
</resultMap>
```
在代码中,可以直接通过调用SqlSession的selectOne方法来获取订单及其所有订单明细:
```
Order order = sqlSession.selectOne("getOrderWithDetails", orderId);
```
其中,Order类和OrderDetail类分别表示订单和订单明细的实体类,details属性表示订单的所有订单明细。