案例描述
通过一个简单的案例实现SpringBoot+Mybatis+ShardingJdbc分库分表实践
通过商品表(good)进行演示:最简单的good表有三个属性:id,good_name, good_type
- 根据id进行分库,当id<=20时使用database0,id>20时,使用database1
- 根据good_type进行分表:当good_type为偶数时,使用good_0,当good_type为奇数时,使用good_1
创建数据库
通过MySQL进行相应代码展示:
create database database0;
use database0;
create table `good_0`(
id bigint(20) primary key ,
good_name varchar(64) COLLATE utf8_bin default '',
good_type bigint(20) default 0
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_bin;
create table `good_1`(
id bigint(20) primary key ,
good_name varchar(64) COLLATE utf8_bin default '',
good_type bigint(20) default 0
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_bin;
create database database1;
use database1;
create table `good_0`(
id bigint(20) primary key ,
good_name varchar(64) COLLATE utf8_bin default '',
good_type bigint(20) default 0
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_bin;
create table `good_1`(
id bigint(20) primary key ,
good_name varchar(64) COLLATE utf8_bin default '',
good_type bigint(20) default 0
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_bin;
以下为项目演示
引入pom文件
<!-- SpringBoot -->
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.2.5.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<!-- MyBatis -->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid