Springboot JPA 集成ShardingSphere

Spring Boot集成JPA与ShardingSphere可通过以下步骤实现分库分表功能,需重点关注依赖配置、分片规则定义及JPA适配问题:

一、依赖配置

1‌. 引入核心依赖‌
在pom.xml中添加ShardingSphere和JPA相关依赖:

<!-- 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‌
在application.yml中关闭自动建表,避免与分表结构冲突:

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. 分表策略‌
按字段哈希分表(如mobile_hash字段):

spring:
  shardingsphere:
    rules:
      sharding:
        tables:
          rainbow_mobile:  # 逻辑表名(对应JPA实体类)
            actual-data-nodes: ds.rainbow_mobile_copy$->{
    
    0..99}  # 实际物理表名
            table-strategy:
              standard:
                sharding-column: mobile_hash
                sharding-algorithm-name: mobile_hash_mod
            key-generate-strategy:
              column: id
              key-generator-name: snowflake  # 使用分布式主键
        sharding-algorithms:
          mobile_hash_mod:
            type: HASH_MOD
            props:
              sharding-count: 100  # 分表总数

三、JPA实体类适配

‌1. 实体类映射‌
使用@Table(name = "rainbow_mobile")指定逻辑表名,无需关注物理表名:

@Entity
@Table(name = "rainbow_mobile")
public class MobileEntity {
    
    
    @Id
    @GeneratedValue(generator = "snowflake")  // 与分片配置的key-generator-name一致
    private Long id;
    private String mobile;
    private String mobile_hash;  // 分片字段
    // Getters & Setters
}

2‌. Repository接口‌
常规JPA查询接口,无需修改:

public interface MobileRepository extends JpaRepository<MobileEntity, Long> {
    
    }

四、注意事项

1‌. 物理表结构一致性‌
分表需预先手动创建物理表(如rainbow_mobile_copy0到rainbow_mobile_copy99),确保表结构完全一致‌。

‌2. 分片字段必传‌
写入或查询时需包含分片字段(如mobile_hash),否则触发全表路由导致性能下降‌。

‌3. 主键生成策略‌
避免使用数据库自增ID,推荐采用ShardingSphere提供的SNOWFLAKE算法,保证分布式环境下主键唯一‌。

‌4. 事务管理‌
若涉及跨分片操作,需结合XA或Seata等分布式事务方案,确保数据一致性‌。