注意使用雪花ID的话,查询ID时候必须使用long类型的ID,不要使用MP自带的默认的Serializable类型。否则会提示分片主键id数据类型和分片算法不匹配Inline sharding algorithms expression
xxx
and sharding columnxx
not match错误。。。
<!--sharding-jdbc 分库分表-->
<dependency>
<groupId>org.apache.shardingsphere</groupId>
<artifactId>shardingsphere-jdbc-core-spring-boot-starter</artifactId>
<version>5.1.1</version>
</dependency>
<!--jdbc-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-jdbc</artifactId>
</dependency>
<!--Mybatis-plus 代码生成器-->
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-boot-starter</artifactId>
<version>${mybatisplus.verison}</version>
</dependency>
CREATE TABLE `sharding_jdbc_0` (
`shading_table_id` bigint(22) NOT NULL COMMENT 'ID',
`name` varchar(50) DEFAULT NULL COMMENT '名称',
`state` int(2) DEFAULT '1' COMMENT '状态:1有效0无效',
`create_time` datetime DEFAULT NULL COMMENT '创建时间',
`user_id` bigint(22) DEFAULT NULL COMMENT '用户ID',
PRIMARY KEY (`shading_table_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
CREATE TABLE `sharding_jdbc_1` (
`shading_table_id` bigint(22) NOT NULL COMMENT 'ID',
`name` varchar(50) DEFAULT NULL COMMENT '名称',
`state` int(2) DEFAULT '1' COMMENT '状态:1有效0无效',
`create_time` datetime DEFAULT NULL COMMENT '创建时间',
`user_id` bigint(22) DEFAULT NULL COMMENT '用户ID',
PRIMARY KEY (`shading_table_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
.........省略其他表。。。。。。。。
mybatis-plus:
type-aliases-package: com.gton.user.entity
mapper-locations: classpath*:com/gton/user/mapper/xml/*Mapper.xml
configuration:
map-underscore-to-camel-case: true #开启驼峰命名
cache-enabled: false #开启二级缓存
log-impl: org.apache.ibatis.logging.stdout.StdOutImpl # 控制台日志
check-config-location: true # 检查xml是否存在
type-enums-package: com.gton.enumPackage #通用枚举开启
global-config:
db-config:
logic-not-delete-value: 1
logic-delete-field: isDel
logic-delete-value: 0
注意yml的配置格式严格要求,错一个空格都不行
spring:
shardingsphere:
datasource:
names: masterdb,ds02
masterdb:
type: com.zaxxer.hikari.HikariDataSource
driverClassName: com.mysql.jdbc.Driver
# 正常的连接数据库
url: jdbc:mysql://127.0.0.1:3306/study?zeroDateTimeBehavior=convertToNull&useSSL=false&useUnicode=true&characterEncoding=UTF-8
username: root
password: root
ds02:
type: com.zaxxer.hikari.HikariDataSource
driverClassName: com.mysql.jdbc.Driver
# 正常的连接数据库
url: jdbc:mysql://127.0.0.1:3306/study?zeroDateTimeBehavior=convertToNull&useSSL=false&useUnicode=true&characterEncoding=UTF-8
username: root
password: root
props:
# 日志显示SQL
sql.show: true
rules:
sharding:
# 表的分片策略
tables:
# 逻辑表的名称
sharding_jdbc:
# 数据节点配置,采用Groovy表达式
actual-data-nodes: masterdb.sharding_jdbc_$->{0..9}
# 配置策略
table-strategy:
# 用于单分片键的标准分片场景
standard:
sharding-column: shading_table_id
# 分片算法名字
sharding-algorithm-name: use-inline
key-generate-strategy: # 主键生成策略
column: shading_table_id # 主键列
key-generator-name: snowflake # 策略算法名称(推荐使用雪花算法)
key-generators:
snowflake:
type: SNOWFLAKE
sharding-algorithms:
use-inline:
type: INLINE
props:
# 分片算法行表达式,需符合groovy语法 '& Integer.MAX_VALUE' 位运算使hash值为正数, 取模运算
# algorithm-expression: sharding_jdbc_$->{(id.hashCode() & Integer.MAX_VALUE) % 9}
# 获取id取模范围为0-10, 包含0, 不包含10
algorithm-expression: sharding_jdbc_$->{shading_table_id % 10}
mode:
type: memory
/**
* (ShardingJdbc1)表实体类
*
* @author 郭童
* @since 2023-05-20 14:58:06
*/
@Data
@Accessors(chain = true)
@ApiModel(value = "ShardingJdbc1", description = "EasyCode")
public class ShardingJdbc implements Serializable {
private static final long serialVersionUID = 1L;
@TableId(type = IdType.ASSIGN_ID)
@ApiModelProperty("ID")
private Long shadingTableId;
@TableField(value = "name")
@ApiModelProperty("名称")
private String name;
@TableField(value = "state")
@ApiModelProperty("状态:1有效0无效")
private Integer state;
@TableField(value = "create_time", fill = FieldFill.INSERT)
@ApiModelProperty("创建时间")
@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss")
private LocalDateTime createTime;
@TableField(value = "user_id")
@ApiModelProperty("用户ID")
private Long userId;
}
/**
* (ShardingJdbc1)表数据库访问层
*
* @author 郭童
* @since 2023-05-20 14:58:06
*/
@Mapper
public interface ShardingJdbcMapper extends EasyBaseMapper<ShardingJdbc> {
}
/**
* @description: EasyBaseMapper<T> extends BaseMapper<T>
* @author: GuoTong
* @createTime: 2022-12-06 16:29
* @since JDK 1.8 OR 11
**/
public interface EasyBaseMapper<T> extends BaseMapper<T> {
/**
* 批量插入 仅适用于mysql
*
* @param entityList 实体列表
* @return 影响行数
*/
Integer insertBatchSomeColumn(Collection<T> entityList);
}
/**
* 通过主键查询单条数据
*
* @param id 主键
* @return 单条数据
*/
@GetMapping("/queryOne/{id}")
public Resp<ShardingJdbc> selectOne(@PathVariable("id") Long id) {
QueryWrapper<ShardingJdbc> queryWrapper = new QueryWrapper<>();
queryWrapper.eq("shading_table_id", id);
return Resp.Ok(this.shardingJdbcService.getOne(queryWrapper));
}
/**
* 新增数据
*
* @param shardingJdbc 实体对象
* @return 新增结果
*/
@PostMapping("/save")
public Resp<String> insert(@RequestBody ShardingJdbc shardingJdbc) {
boolean save = false;
String executeMsg = null;
try {
save = this.shardingJdbcService.save(shardingJdbc);
executeMsg = "新增成功,id 是:" + shardingJdbc.getShadingTableId();
} catch (Exception e) {
executeMsg = e.getMessage();
}
return save ? Resp.Ok(executeMsg) : Resp.error(executeMsg);
}
新增
查询