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