基于shardingsphere-jdbc进行单库分表
<dependencies>
<dependency>
<groupId>org.apache.shardingsphere</groupId>
<artifactId>shardingsphere-jdbc-core-spring-boot-starter</artifactId>
<version>5.1.0</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
</dependencies>
spring:
application:
name: jdbc-jpa-table
profiles:
include: jdbc
jpa:
show-sql: true
hibernate:
ddl-auto: none
naming:
implicit-strategy: org.springframework.boot.orm.jpa.hibernate.SpringImplicitNamingStrategy
physical-strategy: org.springframework.boot.orm.jpa.hibernate.SpringPhysicalNamingStrategy
database-platform: org.hibernate.dialect.MySQL8Dialect
properties:
hibernate.enable_lazy_load_no_trans: true
logging:
file:
name: logs/${spring.application.name}.log
level:
org.springframework: info
com.lance.sharding.table: debug
spring:
shardingsphere:
datasource:
ds:
type: com.zaxxer.hikari.HikariDataSource
driver-class-name: com.mysql.cj.jdbc.Driver
jdbc-url: jdbc:mysql://127.0.0.1:3306/bbs_1?serverTimezone=UTC&useSSL=false&useUnicode=true&characterEncoding=UTF-8
password: li123456
username: root
names: ds
rules:
sharding:
binding-tables:
- t_order,t_order_item
broadcast-tables: t_address
sharding-algorithms:
t-order-inline:
type: INLINE
props:
algorithm-expression: t_order_$->{order_id % 2}
t-order-item-inline:
type: INLINE
props:
algorithm-expression: t_order_item_$->{order_id % 2}
tables:
t_order:
actual-data-nodes: ds.t_order_$->{0..1}
table-strategy:
standard:
sharding-algorithm-name: t-order-inline
sharding-column: order_id
t_order_item:
actual-data-nodes: ds.t_order_item_$->{0..1}
table-strategy:
standard:
sharding-algorithm-name: t-order-item-inline
sharding-column: order_id
props:
sql-show: true
CREATE TABLE `t_order_0`
(
`order_id` bigint NOT NULL AUTO_INCREMENT,
`user_id` int NOT NULL,
`address_id` bigint NOT NULL,
`status` tinyint NULL DEFAULT NULL,
`creator` varchar(32) NULL DEFAULT NULL,
`create_time` datetime NULL DEFAULT NULL,
`updater` varchar(32) NULL DEFAULT NULL,
`update_time` datetime NULL DEFAULT NULL,
PRIMARY KEY (`order_id`) USING BTREE
) ENGINE = InnoDB AUTO_INCREMENT = 1 CHARACTER SET = utf8 COLLATE = utf8_general_ci ROW_FORMAT = Dynamic;
@Slf4j
@SpringBootTest
class OrderRepositoryTests {
@Autowired
private OrderRepository orderRepository;
@Test
//@Disabled
void save() {
ThreadLocalRandom random = ThreadLocalRandom.current();
IntStream.range(20, 41).forEach(i -> {
OrderEntity order = new OrderEntity();
order.setOrderId(System.currentTimeMillis());
order.setAddressId(i);
order.setUserId(Math.abs(random.nextInt()));
order.setCreator("user.0" + i);
order.setCreateTime(new Date());
order.setUpdater(order.getCreator());
order.setUpdateTime(new Date());
orderRepository.save(order);
});
}
}