shardingsphere mybatisplus
时间: 2025-02-07 13:58:25 浏览: 35
### 集成ShardingSphere与MyBatisPlus
#### 项目准备
为了成功集成ShardingSphere与MyBatisPlus,在开始之前需确保环境已准备好。创建一个新的Spring Boot项目并引入必要的依赖项,包括`shardingsphere-jdbc-spring-boot-starter`和`mybatis-plus-boot-starter`。
```xml
<dependency>
<groupId>org.apache.shardingsphere</groupId>
<artifactId>shardingsphere-jdbc-spring-boot-starter</artifactId>
<version>5.2.0</version>
</dependency>
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-boot-starter</artifactId>
<version>3.4.3</version>
</dependency>
```
#### 数据源配置
定义多个数据源用于测试读写分离效果。通过application.yml文件中的配置指定主库和从库的信息[^4]:
```yaml
spring:
shardingsphere:
datasource:
names: master,slave_0
master:
type: com.zaxxer.hikari.HikariDataSource
driver-class-name: com.mysql.cj.jdbc.Driver
jdbc-url: jdbc:mysql://localhost:3306/master_db?useSSL=false&serverTimezone=UTC
username: root
password: root
slave_0:
type: com.zaxxer.hikari.HikariDataSource
driver-class-name: com.mysql.cj.jdbc.Driver
jdbc-url: jdbc:mysql://localhost:3307/slave_db?useSSL=false&serverTimezone=UTC
username: root
password: root
rules:
readwrite-splitting:
data-sources:
default:
static-strategy:
write-data-source-name: master
read-data-source-names: slave_0
```
#### 实体类映射
利用MyBatisPlus简化实体操作,只需继承自BaseMapper接口即可完成基本CRUD方法的封装[^3]。
```java
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import org.apache.ibatis.annotations.Mapper;
@Mapper
public interface UserMapper extends BaseMapper<User> {
}
```
#### 加密字段处理
对于敏感信息存储需求场景下,可以借助ShardingSphere提供的内置加密算法支持来保护特定列的数据安全。注意调整表结构设计时区分物理列名(实际存于DB内的名称)同逻辑列名(应用程序层面所见)[^2]。
```properties
spring.shardingsphere.rules.encrypt.tables.user.columns.password.plain-column=password_plain cipher-column=password_cipher encryptor.name=aes_encryptor
```
以上设置表明password字段将被AES方式进行加解密转换;plain-column代表未加密前原始值所在位置而cipher-column则是经过编码后的最终形态保存之处。
#### 测试验证
编写单元测试案例检验上述配置是否生效以及业务逻辑能否正常运作。例如查询某个用户的详情记录,并打印其密码部分以确认已被妥善隐藏显示。
```java
@Test
void testSelectUser() {
List<User> users = userMapper.selectList(null);
System.out.println(users.get(0).getPassword());
}
```
阅读全文
相关推荐


















