每日总结[6]20191006 Mybatis之关联映射

(1)头脑风暴:把我能想到的写下来:
在我们的数据库中,Order表是主表,从Order表到User表是一对一的关系,因此使用标签完成关联映射,比如sql语句是:

select order.*,user.id,user.username,user.address
from order,user
where order.user_id=user.id

在OrderMapper.xml中写:

<resultMap id="queryOrderByUser" type="com.bit.po.Order">
<id column="id" property="id"/>
<result column="user_id" property="userid"/>
</resultMap>
......>

返回的是List<Order>,因为用的是<resultMap>,所以一定是要返回原类型的,这样它才可以去调用getter、setter方法,不能使用其扩展类和包装类。
<result column>对应的是数据库中表的列名,<property>对应的Order类的属性名。写最终输出结果需要的所有属性。
因为从Order到User是一对一的映射,因此使用<assication>

<assciation id="user" javaType="com.bit.po.User">
<id column="id" property="id"/>
<result column="id" property="id"/>
<result column="username" property="username/">
<result column="sex" property="sex/">
<result column="address" property="address/">
</assciation>

[改:

]
正是因为这里的所以需要在order类中添加User类的user属性。

这里的id名是数据库中的表名,而要能从Order表中得到User,那么需要在Order类中新增User类的属性user。需要在<result column>中写所有在sql语句中被select了的ueser表中的那些属性。
从Order表到Orderdetail表
写sql语句:

select order.*,user.id,user.username,user.address,orderdetail.items_num
from order,user,orderdetail
where order.user_id=user.id
and items.createtime=order.createtime

从Order表到Orderdetail表是一对多的关系,(同理,需要在Order类中新增Orderdetail类型的属性)
使用<collection>:

<collection id="orderdetail" ofType="com.bit.po.orderdetail">
<id column="id" property="id"/>
<result map="items_num" property="itemsNum"/>
</collection>

[改:]

<collection property>

Oftype的类型一般都是List<>或者Map<>中<>包着的类型。
最后,是从Order表到Items表,Order的列名有:
id | user_id | number | createtime| note |,
而items表的列名有:
id | name| price|detail| pic| createtime,
可以看到,他们之间的主键“id”之间是没有直接关系的,倒是可以通过Order的id
Order想要与items表有关系,应当通过OrderDetail表,Orderdetail表的列名:
id | orders_id | items_id | items_num |
应当使items.id=orderdetail.items_id and ordertail.orders_id=orders_id
所以,可以写sql语句:

 select order.*,items.price,items.name,orderdetail.
 from order,items,orderdetail
 where items.id=orderdetail.items_id and ordertail.orders_id=orders_id

这个resultmap中:

<resultMap id="queryitemsByOrder" type="com.bit.po.Order">
<关于Order类的result column property>
<collection>
<关于orderdetail的result column property>
<association>
<关于items的result column property>
</association>
</collection>
</resultMap>

从order表到orderdetail表是一对多的关系,所以使用<collection>,而其中需要嵌套从orderdetail表到item表是一对一的关系,所以使用<association>

注意:中可以使用扩展类、包装类,在中使用的是原类型Order类。

发布了47 篇原创文章 · 获赞 1 · 访问量 1281

猜你喜欢

转载自blog.csdn.net/weixin_41750142/article/details/102287279
今日推荐