MyBatis Review——多对多映射

来源:互联网 发布:怎样开通淘宝食品 编辑:程序博客网 时间:2024/06/03 13:42


示例:  

              查询用户及用户购买商品信息。


sql语句:


SELECTorders.*, USER .username ,USER .sex,USER .address,orderdetail.id as orderdetail_id,orderdetail.items_id,orderdetail.items_num,orderdetail.orders_id,items.`name` items_name,items.detail items_detail,items.price items_priceFROMorders,USER,orderdetail,  itemsWHEREorders.user_id = USER .idAND  orderdetail.orders_id=orders.idand orderdetail.items_id=items.id

查询结果:




resultMap对应pojo:




Orders:




OrderDetials:





resultMap:



<resultMap type="User" id="UserAndItemsResultMap"><!-- 用户信息 --><id column="user_id" property="id" /><result column="username" property="username" /><result column="sex" property="sex" /><result column="address" property="address" /><!-- 订单信息 --><collection property="ordersList" ofType="cn.itcast.mybatis.po.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="orderDetials" ofType="cn.itcast.mybatis.po.OrderDetial"><id column="orderdetail_id" property="id" /><result column="items_id" property="itemsId" /><result column="items_num" property="itemsNum" /><result column="orders_id" property="ordersId" /><association property="items" javaType="cn.itcast.mybatis.po.Items"><id column="items_id" property="id" /><result column="items_name" property="name" /><result column="items_detail" property="detail" /><result column="items_price" property="price" /></association></collection></collection></resultMap>


【小结】:

       

resultType

作用:

将查询结果按照sql列名pojo属性名一致性映射到pojo中。

场合:

常见一些明细记录的展示,比如用户购买商品明细,将关联查询信息全部展示在页面时,此时可直接使用resultType将每一条记录映射到pojo中,在前端页面遍历listlist中是pojo)即可。

 

resultMap

使用associationcollection完成一对一和一对多高级映射(对结果有特殊的映射要求)。

 

association

作用:

将关联查询信息映射到一个pojo对象中。

场合:

为了方便查询关联信息可以使用association将关联订单信息映射为用户对象的pojo属性中,比如:查询订单及关联用户信息。

使用resultType无法将查询结果映射到pojo对象的pojo属性中,根据对结果集查询遍历的需要选择使用resultType还是resultMap

collection

作用:

将关联查询信息映射到一个list集合中。

场合:

为了方便查询遍历关联信息可以使用collection将关联信息映射到list集合中,比如:查询用户权限范围模块及模块下的菜单,可使用collection将模块映射到模块list中,将菜单列表映射到模块对象的菜单list属性中,这样的作的目的也是方便对查询结果集进行遍历查询。

如果使用resultType无法将查询结果映射到list集合中。



0 0
原创粉丝点击