00:00
这节课呢,我们来讲一下多表关联的情况,那么我们准备创建一组T表,和T表进行关联,T呢是订单表,那么t order item呢,就是订单详情表,在订单详情表里面我们有这样的一些字段,第一个呢就是订单详情的ID,那么他呢也没有设置主键自增,所以呢,他的策略和订单表的策略是一样的。我们会使用分布式ID生成算法来生成这个ID,接下来呢,就是order number,那一个订单呢,可能会对应多个订单详情,因为我们在一个订单当中可能会买多个商品,那每一个商品呢,会对应一个订单详情信息,那所以呢,在我们的订单详情表里面呢,就会有一个order number作为和订单表的关联,当然了,在实际情况下,我们在做数据库表设计的时候呢,其实呢,你也可以用order ID来做这个关联关系,但是为什么在这个里面我们没有用ID而用了呢呢?在后面我们的定表当中,我们再去讲哈。
01:07
然后接下来呢,我们还有一个字段呢,叫user ID,那user ID呢,我们把它设计在订单详情表里呢,目的是我们希望同一个用户的订单表和订单详情表中的数据呢,都会被插入到同一个数据源当中,这样的话呢,如果我们找同一个用户的订单和订单详情表做关联查询的时候呢,这样的话呢,可以避免跨库关联,那因为呢,我们会通过UCID对这两张表呢,做一个数据库的分片设置,所以呢,相同的UCIID的订单表和订单详情表呢,就会被分配到同一个数据库当中,好然后呢,这个呢,就是我们的订单详情当中的商品的单价,那这个呢,是我们订单详情当中商品的数量,因为我们买商品的时候呢,可能一个商品可以买很多,比如说我买了两盒月饼,然后两个水杯等等等等,所以呢,这个呢,就是订单详情表的。
02:08
商品的数量好,那这个呢,就是订单详情表的一个数据结构了,那接下来呢,我们把这个数据结构呢,创建在我们的数据库中。我们先把它创建在这个数据库服务器中。选中DB order。好,我们来看一下有没有创建出来。那这两张表就创建出来下,我们再把这表呢,创建在serve这个数据服务中。好,我们刷新一下,那这两张表呢,也创建出来了,然后呢,针对item表呢,我们来创建实体类。那这个就是实体类了。
03:00
好,这个里面的字段呢,也很明显,第一就是ID,那么这个ID呢,我们和order这个实体类呢,用一样的策略,就是ID type,那么后面呢,我们会在配置文件当中去配置B的分布式序列,好然后接下来呢,就是user个义我。好,这个是实体类的一个添加,最后呢,我们把map文件给它添加上,那么这个呢,对应的就是刚刚我们创建的it。这个实体。接口好。X被。Order item。
04:00
好,那么接下来呢,我们来做关联表的配置,那么关联表我们需要配置order item的分片表,以及分片策略,还有分布式序列的策略,那么所有的这些配置呢,其实呢都和是一致的,所以我们打开配置文件看一看。都要进行什么样的配置。我们先把这个。配置文件呢,给他做一个备份。叫水平分片。好,然后呢,在新复制的这个文件当中呢,我们首先先来看一下,前面是不变的,然后数据源也是不变的,现在依然是这样的几个数据源。那我们需要添加一个标准分片表配置,把我们最新的order item表给它配置上,所以这个地方呢,叫7ORDER item。
05:00
然后这块呢,是和当中的。好,这个是节点的配置,然后呢,我们要配分库策略,分库策略呢,我们让t order item和T的分库策略一致。这就是我们前面所说的,这样的话呢,相同的ID的数据呢,无论是T还是我们现在配的都会在同一个数据库当中,这样的话,我们对T和t it做关联查询的时候呢,就避免了跨库的关联。好。那后面不变,分片策略是一致的,分片算法呢也是一致的。接下来呢,我们来看分表策略,分表策略呢,也和我们的order是一样的,所以这块呢,我们写order item。
06:04
好。后面这块呢,我们的分片键呢,也是order number,好,然后呢,分片算法呢,也都是一样的。接下来分算法配置,那我们用的呢,就是这里面刚才的mode呀,Mode呀,还有呀这些算法哈,所以这块就不需要重复的配置了,因为他们是共享的。然后呢,是分布式序列的配置,那这个呢是T的分布式序列,我们对t it呢也配置相同的分布式序列。好,那么。ID列呢,依然是ID。我们的ID列的分布式序列的算法呢,依然用的是flake。那后面这个也是共享,所以就不用配置了,那到这为止呢,针对的配置呢,就暂时告一段落,那接下来呢,我们可以对整个的过程呢,做一个测试,我们做什么测试呢?先我们先做一个数据插入的测试。
07:15
好,我们打开test。然后呢,在这里面我们做一个数据插入的测试,我们先把这段代码给它复制过来。这个是插入订单的,我们在插入订单的同时呢,再插入一些。订单项。所以拿这块呢,是测试关联表插入好,那这块呢,我们写S。那这块呢,我们依然是I等于一到五,然后下面呢,我们依然是I等于五到九。
08:06
然后上面这一部分呢,我们是给用户ID为一的用户添加记录,下面这一部分呢,我们是给用户ID为二的用户添加记录,那当然了,这个订单金额呢,我们就不在这儿去设置了哈。那实际上订单金额是根据订单项最后统计出来的,所以最后呢,我们会做一个订单金额的统计。然后接下来呢,在这个里面,我们为每一个订单呢,都插入若干个订单项。那这边呢,我们就简单的写一个for循环吧,我们这个J呢,就等于。三吧,好。那这样的话呢,我们每一个订单呢,插入三个订单项ID,不用我们去创建,它是默认的。
09:08
逐渐策略,然后接下来呢。我们的订单项和订单之间要通过这个做关联,所以这两个必须是一致的。点user ID,那么user ID呢,也是一个分策略,它要和的这个user ID要保持一致。好,那么就是这个订单下面的这些订单项,肯定是属于同一个订单,同一个用户的,对不对?好,然后接下来呢,我们给每一个订单项呢,添加一个。商品单价price。我们随便写一个,比如说十块钱。好,然后呢,我们添加一个商品的数量,那这块应该是A商品数量,比如说每个商品买两份。
10:12
然后呢,这面是order a map,我们需要把order item map呢。住到前面好,然后我们用order去做数据的插入。那么我们插入的是order item这个记录。接下来呢,在下面。这个位置呢,我们在针对UID为二的用户呢,在添加同样的订单项。那这边我们对照一下,这是一样的,然后这块呢,得写个二。那这个金额呢,我们稍微变化一下吧,比如这金额我们就写三。
11:02
然后商品的数量,我们买了三个。那这是我们的一个插入的测试用例。好在测试之前呢,我们把前面有一个map,我们没有添加map注解哈,给它先填上。然后呢,我们来测试一下。好,那这样的话呢,就添加进了若干个记录在我们的数据库中,我们直接在数据库中看结果吧,我们先来看零这个数据库。那么这个里面呢,有order it0 order it1 order0和ORDER1都被插入进来了,然后这面也是一样的。有ORDER1 order0 ato1和order ato0。
我来说两句