Mybatis3 resultMap 官方应用

### MyBatis 中 `collection` 标签与 `resultMap` 的使用方法 #### 1. 理解 `resultMap` `resultMap` 是 MyBatis 中最强大的功能之一,用于定义如何将 SQL 查询的结果映射到 Java 对象。通过 `resultMap` 可以实现复杂的映射逻辑,包括一对一、一对多的关系处理。 ```xml <resultMap id="userResultMap" type="User"> <id property="id" column="user_id"/> <result property="username" column="username"/> </resultMap> ``` 这段代码展示了最基本的 `resultMap` 定义方式[^1]。 #### 2. 使用 `<collection>` 标签处理一对多关系 当涉及到一对多关系时,可以利用 `<collection>` 标签来完成这种复杂的数据映射。例如,在用户和订单之间存在的一对多关系可以通过如下方式进行配置: ```xml <resultMap id="orderListResultMap" type="Order"> <!-- 映射简单字段 --> <id property="orderId" column="order_id"/> <result property="amount" column="total_amount"/> <!-- 配置 collection 来表示多个 OrderItem 实体 --> <collection property="items" ofType="OrderItem"> <id property="itemId" column="item_id"/> <result property="itemName" column="name"/> <result property="quantity" column="quantity"/> </collection> </resultMap> ``` 上述 XML 片段说明了在一个订单中有多个商品项的情况下的映射设置[^3]。 #### 3. 结合实际案例分析 假设有一个场景:一个客户拥有多个地址记录,则可以在对应的 Mapper 文件中做如下设定: ```xml <!-- Customer.java 类对应 customer 表 --> <resultMap id="customerWithAddresses" type="Customer"> <id property="customerId" column="cust_id"/> <result property="name" column="cust_name"/> <!-- Address 列表作为 Customer 的属性 --> <collection property="addresses" javaType="ArrayList" ofType="Address" select="selectAddressesByCustomerId" column="{custId=customerId}"> <id property="addressId" column="addr_id"/> <result property="street" column="street"/> <result property="city" column="city"/> </collection> </resultMap> <select id="selectAddressesByCustomerId" resultType="Address"> SELECT * FROM addresses WHERE cust_id = #{custId} </select> ``` 这里不仅指定了 `property` 和 `ofType` 参数,还额外引入了一个子查询 (`select`) 方法来获取关联的对象列表,并传递必要的参数给它[^5]。 #### 4. 关键点总结 - `collection`: 主要用来解决实体间的一对多关系问题; - `javaType`: 指定集合的具体类型,默认为 `ArrayList`; - `ofType`: 设置集合内元素的目标类型; - 支持两种模式——嵌套结果(`nested results`) 和 嵌套查询(`nested query`); 对于更高级的应用场合,还可以考虑采用延迟加载等特性优化性能表现[^4]。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值