数据库详情见上一篇
一对多的情况如下:
- 查询客户ID为4的所有订单的信息。
方法一:
<mapper namespace="com.blb.mapper.UserMap">
<!-- 一对多 -->
<resultMap id="aaa" type="Customer">
<id property="id" column="id"></id>
<result property="name" column="name"></result>
<collection property="orders" select="queryOrderById" column="id"></collection>
</resultMap>
<select id="queryCustomById" resultMap="aaa">
select * from t_customer where id = #{id}
</select>
<select id="queryOrderById" resultType="Order">
select * from t_order where c_id = #{id}
</select>
</mapper>
这种方法比较容易理解,需要查询两次才能返回自己所想要的结果。主要是利用自定义结果集resultMap,在collection属性中使用select属性关联另外一张表达查询方法,column属性传递上一次查询数据库的字段属性,作为参数传递给下一个查询,变成它所需要的条件。
方法二:
<mapper namespace="com.blb.mapper.UserMap">
<!-- 一对多 -->
<resultMap id="aaa" type="com.blb.entity.Customer">
<id property="id" column="id"></id>
<result property="name" column="name"></result>
<collection property="orders" ofType="com.blb.entity.Order">
<id property="id" column="oid"></id>
<result property="orderName" column="order_name"></result>
</collection>
</resultMap>
<select id="getById" resultMap="aaa">
select c.*, o.id oid, o.order_name from t_customer c, t_order o where c.id = o.c_id and c.id=2
</select>
</mapper>
这种方法使用起来会更加快速,因为只用查询一次。同样也是利用自定义结果集resultMap,但是在collection 属性中需要用到ofType来指定对应存放数据的实体类,然后继续将该实体类中的字段与数据库中的字段一一对应起来。值得注意的是,现在利用的是联合查询方式,要看数据库里查询的结果显示的字段是否有重复。我这里id有重复,两个表的主键都设置的是id,所以联合查询的时候,相同字段会发生改变不便于观察。需要使用重命名的方式查询,并且将重命名的字段写入collection 属性里对应的子类id 属性对应的column属性中。
再有一点需要注意到是:collection 属性里可以不用添加完整的实体类字段。前提是查询语句中的selcet包含该实体类在数据库中的相应字段。