Spring Boot集成JPA与ShardingSphere实现按年分表,需重点关注分片算法选择、时间字段映射及动态表管理。以下是实现方案:
一、依赖配置
1. 核心依赖引入
<!-- ShardingSphere JDBC -->
<dependency>
<groupId>org.apache.shardingsphere</groupId>
<artifactId>shardingsphere-jdbc-core-spring-boot-starter</artifactId>
<version>5.3.2</version>
</dependency>
<!-- Spring Data JPA -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
2. 禁用Hibernate自动DDL
spring:
jpa:
hibernate:
ddl-auto: none # 避免自动建表与分表冲突
二、分片规则配置
1. 数据源定义(单库分表)
spring:
shardingsphere:
datasource:
names: ds
ds:
driver-class-name: com.mysql.cj.jdbc.Driver
url: jdbc:mysql://localhost:3306/test_db
username: root
password: root
2. 按年分表策略
spring:
shardingsphere:
rules:
sharding:
tables:
order: # 逻辑表名(对应JPA实体)
actual-data-nodes: ds.order_$->{2020..2030} # 物理表格式:order_2020, order_2021...
table-strategy:
standard:
sharding-column: create_time # 分片字段(时间类型)
sharding-algorithm-name: order_year_interval
sharding-algorithms:
order_year_interval:
type: INTERVAL # 时间范围分片算法
props:
datetime-pattern: "yyyy-MM-dd HH:mm:ss" # 时间字段格式
datetime-lower: "2020-01-01 00:00:00" # 起始年份
datetime-upper: "2030-12-31 23:59:59" # 结束年份
sharding-suffix-pattern: "yyyy" # 表后缀格式(按年)
datetime-interval-amount: 1 # 分片间隔(1年)
三、JPA实体类适配
1. 实体类映射逻辑表
@Entity
@Table(name = "order") // 对应逻辑表名
public class Order {
@Id
@GeneratedValue(generator = "snowflake")
private Long id;
@Column(name = "create_time")
private LocalDateTime createTime; // 分片字段
// 其他字段及Getter/Setter
}
2. Repository接口
public interface OrderRepository extends JpaRepository<Order, Long> {}
四、动态表管理(可选)
1. 自动建表逻辑
- 方案1:启动时检测并执行DDL
通过DataSourceInitializer检查物理表是否存在,若不存在则动态创建:
CREATE TABLE IF NOT EXISTS order_2025 (
id BIGINT PRIMARY KEY,
create_time DATETIME,
-- 其他字段
);
- 方案2:自定义分片算法扩展
继承AutoCreateAlgorithm接口,在数据插入时自动创建缺失的年度表。
五、注意事项
1. 分片字段必传
写入或查询时必须包含create_time字段,否则触发全表路由。
2. 跨年查询支持
ShardingSphere自动合并多个年度表数据,但需避免全表扫描(如WHERE create_time BETWEEN ‘2024-01-01’ AND ‘2025-12-31’)。
3. 时间范围边界
配置datetime-lower和datetime-upper时需预留足够年份,超出范围会导致路由失败。
通过以上配置,JPA操作逻辑表order时,数据将按create_time年份自动路由到order_2024、order_2025等物理表,实现按年分表存储。