一、什么是公共表?
1)存储固定数据的表,表数据很少发生变化,查询的时候经常进行关联;
2)在每个数据库中都创建出相同结构的公共表
3)在我们操作这张表的时候,每个数据库中的公共表的数据也会随之改变
二、演示步骤
1、在每个数据库中都创建公共表
2、创建实体类和mapper
3、编写配置文件
#分片策略配置#配置数据源名称, 水平分库,需要配置两个数据源spring.shardingsphere.datasource.names=db1,db2,db3#配置第一个数据源spring.shardingsphere.datasource.db1.type=com.alibaba.druid.pool.DruidDataSourcespring.shardingsphere.datasource.db1.driver-class-name=com.mysql.cj.jdbc.Driverspring.shardingsphere.datasource.db1.url=jdbc:mysql://172.16.235.3:3306/course_db_1?serverTimezone=GMT%2B8spring.shardingsphere.datasource.db1.username=rootspring.shardingsphere.datasource.db1.password=123456#配置第二个个数据源spring.shardingsphere.datasource.db2.type=com.alibaba.druid.pool.DruidDataSourcespring.shardingsphere.datasource.db2.driver-class-name=com.mysql.cj.jdbc.Driverspring.shardingsphere.datasource.db2.url=jdbc:mysql://172.16.235.3:3306/course_db_2?serverTimezone=GMT%2B8spring.shardingsphere.datasource.db2.username=rootspring.shardingsphere.datasource.db2.password=123456#配置第三个数据源spring.shardingsphere.datasource.db3.type=com.alibaba.druid.pool.DruidDataSourcespring.shardingsphere.datasource.db3.driver-class-name=com.mysql.cj.jdbc.Driverspring.shardingsphere.datasource.db3.url=jdbc:mysql://172.16.235.3:3306/user_db?serverTimezone=GMT%2B8spring.shardingsphere.datasource.db3.username=rootspring.shardingsphere.datasource.db3.password=123456#配置user_db里t_user的分库规则spring.shardingsphere.sharding.tables.t_user.actual-data-nodes=db$->{3}.t_userspring.shardingsphere.sharding.tables.t_user.key-generator.column=user_idspring.shardingsphere.sharding.tables.t_user.key-generator.type=SNOWFLAKEspring.shardingsphere.sharding.tables.t_user.database-strategy.inline.sharding-column=user_idspring.shardingsphere.sharding.tables.t_user.database-strategy.inline.algorithm-expression=t_user#配置公共表spring.shardingsphere.sharding.binding-tables=t_pubspring.shardingsphere.sharding.tables.t_pub.key-generator.column=pub_idspring.shardingsphere.sharding.tables.t_pub.key-generator.type=SNOWFLAKE....
4、编写测试代码
@Test
void addPub(){
Pub pub = new Pub();
pub.setPubState("1");
pub.setPubValue("正常");
pubMapper.insert(pub);
}
执行之后会发现三个库中的t_pub都有了一条数据,而且所有数据都一样,包括ID
我们再来测试删除
@Test
void delPub(){
QueryWrapper<Pub> queryWrapper = new QueryWrapper<>();
queryWrapper.eq("pub_id",574329541527339009L);
pubMapper.delete(queryWrapper);
}
这个时候三个数据库中的三张表中的pub_id为574329541527339009的数据都删掉了
