两种类型
resultType和resultMap都可以完成输出映射:
- resultType映射要求sql查询的列名和输出映射pojo类型的属性名一致
- resultMap映射时对sql查询的列名和输出映射pojo类型的属性名作一个对应关系。
操作步骤
- 分析需求(主查询表、关联查询表)
- 编写sql语句
- resultMap进行映射的思路,在相应的pojo里加关联
- 编写Usermapper.xml
- 定义resultMap
- 编写Usermapper.java
一对一映射
<select id="findOrderUserListResultMap" resultMap="ordersUserResultMap">
XXX(sql语句)
</select>
<!--一对多,查询订单及订单明细-->
<!--type是mapper映射返回方法返回的结果-->
<resultMap type="pojo.Orders" id="ordersUserResultMap">
<!--完成订单信息的映射-->
<!--id是用来唯一标识用户查询-->
<id column="id" property="id"/>
<result column="user_id" property="userId"/>
<result column="number" property="number"/>
<result column="createtime" property="createtime"/>
<result column="note" property="note"/>
<!--下面完成关联信息的映射 association用户关联信息到单个pojo-->
<!--property为Orders下的某个属性-->
<association property="user" javaType="pojo.User">
<id column="user_id" property="id"/>
<result column="username" property="username"/>
<result column="sex" property="sex"/>
</association>
</resultMap>
//resultMap一对一查询
public List<Orders> findOrderUserListResultMap();
一对多
<!--使用resultMap进行多表查询-->
<select id="findOrderAndOrderDetails" resultMap="orderAndOrderDetailsResultMap">
SELECT
orders.*,
USER.username,
USER.sex,
orderdetail.id orderdetail_id,
orderdetail.items_id
FROM
orders,
USER,
orderdetail
WHERE
orders.user_id = USER.id
AND orders.id = orderdetail.orders_id
</select>
<!--一对多的查询:查询用户表及订单和订单查询-->
<resultMap id="orderAndOrderDetailsResultMap" type="pojo.Orders" extends="ordersUserResultMap">
<!--映射订单信息和用户信息,这里使用继承orderAndOrderDetailsResultMap-->
<!--映射订单明细信息 -->
<collection property="orderdetails" ofType="pojo.Orderdetail">
<id column="orderdetail_id" property="id"></id>
<result column="items_num" property="itemsNum"/>
<result column="items_id" property="itemsId"/>
</collection>
</resultMap>
//resultMap一对多查询
public List<Orders> findOrderAndOrderDetails();
复杂的多表映射关系 - type映射的常为主查询表对象
<!--一对多的复杂查询:查询用户表及订单和订单查询,商品信息-->
<resultMap id="UserorderdetailResultMap" type="pojo.User">
<!--用户查询-->
<id column="user_id" property="id"/>
<result column="username" property="username"/>
<result column="sex" property="sex"/>
<!--订单映射-->
<collection property="ordersList" ofType="pojo.Orders">
<id column="id" property="id"/>
<result column="user_id" property="userId"/>
<result column="number" property="number"/>
<result column="createtime" property="createtime"/>
<result column="note" property="note"/>
<!--订单详情映射-->
<collection property="orderdetails" ofType="pojo.Orderdetail">
<id column="orderdetail_id" property="id"></id>
<result column="items_num" property="itemsNum"/>
<result column="items_id" property="itemsId"/>
<!--商品映射-->
<association property="items" javaType="pojo.Items">
<id column="items_id" property="id"/>
<result column="items_name" property="name"/>
<result column="items_detail" property="detail"/>
</association>
</collection>
</collection>
</resultMap>
网友评论