SpringBoot使用sharding-jdbc分库分表
时间:2021-07-01 10:21:17
帮助过:356人阅读
>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.5.16.RELEASE</version>
<relativePath/>
</parent>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
<java.version>1.8</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>com.dangdang</groupId>
<artifactId>sharding-jdbc-core</artifactId>
<version>1.4.2</version>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>1.0.12</version>
</dependency>
<dependency>
<groupId>com.dangdang</groupId>
<artifactId>sharding-jdbc-self-id-generator</artifactId>
<version>1.4.2</version>
</dependency>
</dependencies>
目前好像不支持SpringBoot2.0以上的版本。
2.2编写实体类及建库建表
目标:
db0
├── t_order_0 user_id为偶数 order_id为偶数
├── t_order_1 user_id为偶数 order_id为奇数
db1
├── t_order_0 user_id为奇数 order_id为偶数
├── t_order_1 user_id为奇数 order_id为奇数
- 创建两个数据库 ds_0 和 ds_1,编码类型UTF-8。
- 每个库分表创建两个表t_order_0和t_order_1,sql语句如下:
DROP TABLE IF EXISTS t_order_0;
CREATE TABLE t_order_0 (
order_id bigint(20) NOT NULL,
user_id bigint(20) NOT NULL,
PRIMARY KEY (order_id)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_bin;
- 新建类Order,代码如下
- package cn.sp.bean;
-
- import javax.persistence.Entity;
- import javax.persistence.Id;
- import javax.persistence.Table;
-
-
-
-
- @Entity
- @Table(name="t_order")
- public class Order {
- @Id
- private Long orderId;
-
- private Long userId;
-
- public Long getOrderId() {
- return orderId;
- }
-
- public void setOrderId(Long orderId) {
- this.orderId = orderId;
- }
-
- public Long getUserId() {
- return userId;
- }
-
- public void setUserId(Long userId) {
- this.userId = userId;
- }
- }
-
这里需要注意 @Id注解不要导错包,之前我就遇到过这个问题。
4.配置文件application.yml
- server:
- port: 8000
- spring:
- jpa:
- database: mysql
- show-sql: true
- hibernate:
-
- ddl-auto: none
- application:
- name: sharding-jdbc-first
这里要注意的是spring-data-jpa默认会自己建表,这里我们要手动建立,所以需要将ddl-auto属性设置为none。
2.3自定义分库分表算法
1.分库算法类需要实现SingleKeyDatabaseShardingAlgorithm<T>接口,这是一个泛型接口,T代表分库依据的字段的类型,比如我们根据userId%2来分库,userId是Long型的,这里的T就是Long。
- public cl