mybatis-plus 租户管理
时间: 2023-06-28 12:12:08 浏览: 76
Mybatis-Plus 是基于 Mybatis 的扩展工具包,它提供了很多实用的功能,其中包括租户管理。
在 Mybatis-Plus 中,租户管理是通过多租户插件实现的。多租户插件提供了对租户的切换和租户信息的获取等功能。
使用多租户插件,需要在 Mybatis 的配置文件中配置插件:
```xml
<!-- 多租户插件 -->
<plugins>
<plugin interceptor="com.baomidou.mybatisplus.extension.plugins.tenant.TenantSqlParser">
<!-- 租户字段名 -->
<property name="tenantColumn" value="tenant_id"/>
<!-- 租户 ID 类型 -->
<property name="tenantIdType" value="long"/>
<!-- 忽略 SQL 解析的表名 -->
<property name="ignoreTable" value="sys_tenant"/>
<!-- 是否支持动态租户切换 -->
<property name="supportTenantSwitch" value="true"/>
</plugin>
</plugins>
```
在使用多租户插件时,可以通过注解的方式指定租户信息:
```java
@TableName(value = "user")
public class User implements Serializable {
@TableId(type = IdType.AUTO)
private Long id;
private String name;
@TableField(value = "tenant_id")
@MultiTenantColumn
private Long tenantId; // 租户 ID
// 省略 getter/setter
}
```
在进行查询时,多租户插件会自动在 SQL 语句中加入租户信息的过滤条件,以保证查询结果只包含当前租户的数据:
```java
// 查询当前租户的所有用户
List<User> userList = userService.list(new QueryWrapper<User>().lambda()
.eq(User::getTenantId, TenantContextHolder.getTenantId()));
```
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)