Table Sharding allows you to split a single logical table into multiple physical tables (e.g., by month).
Configuration Steps:
- Annotate the Entity: Use
@Table with the shardingInitializer attribute. Use @ShardingTableKey on the field used for routing (this does not have to be the primary key). - Create a Sharding Initializer: Implement
AbstractShardingMonthInitializer (or similar) to define the time range (getBeginTime, getEndTime) and optimize performance via configure. - Create a Table Route: Implement
AbstractMonthTableRoute to define how the sharding value (e.g., LocalDateTime) maps to a table.
Example Implementation:
@Table(value = "t_topic_sharding_time", shardingInitializer = TopicShardingTimeShardingInitializer.class)
public class TopicShardingTime {
@Column(primaryKey = true)
private String id;
@ShardingTableKey
private LocalDateTime createTime;
}
public class TopicShardingTimeShardingInitializer extends AbstractShardingMonthInitializer<TopicShardingTime> {
@Override
protected LocalDateTime getBeginTime() { return LocalDateTime.of(2020, 1, 1, 1, 1); }
@Override
protected LocalDateTime getEndTime() { return LocalDateTime.of(2023, 5, 1, 0, 0); }
}
public class TopicShardingTimeTableRoute extends AbstractMonthTableRoute<TopicShardingTime> {
@Override
protected LocalDateTime convertLocalDateTime(Object shardingValue) { return (LocalDateTime) shardingValue; }
}
@Table(value = "t_topic_sharding_time", shardingInitializer = TopicShardingTimeShardingInitializer.class)
public class TopicShardingTime {
@Column(primaryKey = true)
private String id;
private Integer stars;
private String title;
@ShardingTableKey
private LocalDateTime createTime;
}
public class TopicShardingTimeShardingInitializer extends AbstractShardingMonthInitializer<TopicShardingTime> {
@Override
protected LocalDateTime getBeginTime() {
return LocalDateTime.of(2020, 1, 1, 1, 1);
}
@Override
protected LocalDateTime getEndTime() {
return LocalDateTime.of(2023, 5, 1, 0, 0);
}
}
public class TopicShardingTimeTableRoute extends AbstractMonthTableRoute<TopicShardingTime> {
@Override
protected LocalDateTime convertLocalDateTime(Object shardingValue) {
return (LocalDateTime) shardingValue;
}
}