<返回更多

Spring boot 2.x 集成Mybatis-plus 实现多租户

2022-01-10    萧声飞扬
加入收藏

目前线上很多SAAS系统,但是SAAS系统必须支持多租户,对于多租户有多种实现方式,当然不同的实现方式的成本也是不同的。这里我介绍一种最节省成本的实现方式,通过数据记录增加租户标识字段tenant_id的方式。但是每次对数据库操作都要带上租户标识tenant_id是非常不方便,很容易出错。一旦出错就是破坏了SAAS的数据隔离,出现非常严重的事故。本次介绍的Spring boot 2.x 集成Mybatis-plus 通过自动拦截SQL语句并自动填充租户标识tenant_id,

一、创建maven项目zircloud-tenant, pom文件如下:

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.Apache.org/POM/4.0.0"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
	<modelVersion>4.0.0</modelVersion>
	<parent>
		<groupId>org.springframework.boot</groupId>
		<artifactId>spring-boot-starter-parent</artifactId>
		<version>2.6.2</version>
		<relativePath /> <!-- lookup parent from repository -->
	</parent>
	<groupId>com.zircloud.tenant</groupId>
	<artifactId>zircloud-tenant</artifactId>
	<version>0.0.1-SNAPSHOT</version>
	<name>zircloud-tenant</name>
	<description>Demo project for Spring Boot</description>
	<properties>
		<JAVA.version>1.8</java.version>
	</properties>
	<dependencies>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-web</artifactId>
		</dependency>
		<dependency>
			<groupId>org.projectlombok</groupId>
			<artifactId>lombok</artifactId>
			<optional>true</optional>
		</dependency>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-test</artifactId>
			<scope>test</scope>
		</dependency>
		<dependency>
			<groupId>MySQL</groupId>
			<artifactId>mysql-connector-java</artifactId>
			<scope>runtime</scope>
		</dependency>
		<dependency>
			<groupId>com.baomidou</groupId>
			<artifactId>mybatis-plus-boot-starter</artifactId>
			<version>3.5.0</version>
		</dependency>
		<!-- alibaba的druid数据库连接池 -->
		<dependency>
			<groupId>com.alibaba</groupId>
			<artifactId>druid-spring-boot-starter</artifactId>
			<version>1.1.10</version>
		</dependency>
	</dependencies>
	<build>
		<plugins>
			<plugin>
				<groupId>org.springframework.boot</groupId>
				<artifactId>spring-boot-maven-plugin</artifactId>
				<configuration>
					<excludes>
						<exclude>
							<groupId>org.projectlombok</groupId>
							<artifactId>lombok</artifactId>
						</exclude>
					</excludes>
				</configuration>
			</plugin>
		</plugins>
	</build>
</project>

项目结构如下:

Spring boot 2.x 集成Mybatis-plus 实现多租户

 

二、创建Mybatis-plus 配置类 MybatisPlusConfig.java

Mybaits-plus 配置用于自动填充租户标识tenant_id, 忽略不需要填充租户标识tenant_id的数据库表

        package com.zircloud.tenant.config;

import org.mybatis.spring.annotation.MApperScan;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import com.baomidou.mybatisplus.extension.plugins.MybatisPlusInterceptor;
import com.baomidou.mybatisplus.extension.plugins.handler.TenantLineHandler;
import com.baomidou.mybatisplus.extension.plugins.inner.TenantLineInnerInterceptor;

import net.sf.jsqlparser.expression.Expression;
import net.sf.jsqlparser.expression.LongValue;

/**
 * @author test
 * @since 2022年1月10日
 */
@Configuration
@MapperScan("com.zircloud.**.mapper.**")  //要扫描的mapper目录
public class MybatisPlusConfig {

	@Bean
	public MybatisPlusInterceptor mybatisPlusInterceptor() {
		MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();
		interceptor.addInnerInterceptor(new TenantLineInnerInterceptor(new TenantLineHandler() {
			@Override
			public Expression getTenantId() {
				Long tenantId = 1L; //租户标识,可以从服务上下文中获取,
				return new LongValue(tenantId);
			}
			@Override
			public boolean ignoreTable(String tableName) {
				return !"user_info".equalsIgnoreCase(tableName); //配置要忽略多租户的数据库表
			}
		}));
		return interceptor;
	}
}

三、创建的Service、Controller类,

创建的Service、Controller就不用手动填充租户标识tenant_id了

package com.zircloud.tenant.service.impl;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zircloud.tenant.dto.UserInfoDto;
import com.zircloud.tenant.entity.UserInfo;
import com.zircloud.tenant.mapper.UserInfoMapper;
import com.zircloud.tenant.service.UserInfoService;

import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author test
 * @since 2022-01-06
 */
@Service
public class UserInfoServiceImpl extends ServiceImpl<UserInfoMapper, UserInfo> implements UserInfoService {
	
	
	@Autowired
	private UserInfoMapper mapper;

	@Override
	public UserInfoDto getUserByid(Integer id) {
		UserInfo user = mapper.selectById(id);
		if(user!=null) {
			UserInfoDto dto = new UserInfoDto();
			BeanUtils.copyProperties(user, dto);
			return dto;
		}
		return null;
	}

	@Override
	public UserInfoDto getUserByname(String name) {
		QueryWrapper<UserInfo> queryWrapper = new QueryWrapper<UserInfo>();
		queryWrapper.eq("name",name);
		
		UserInfo user = mapper.selectOne(queryWrapper);
		if(user!=null) {
			UserInfoDto dto = new UserInfoDto();
			BeanUtils.copyProperties(user, dto);
			return dto;
		}
		return null;
	}

	@Override
	public boolean creaate(UserInfoDto dto) {
		if(dto!=null) {
			UserInfo user = new UserInfo();
			BeanUtils.copyProperties(dto, user);
			return mapper.insert(user)>0;
		}
		return false;
	}

}

Controller

package com.zircloud.tenant.web;


import javax.annotation.Resource;

import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.zircloud.tenant.dto.UserInfoDto;
import com.zircloud.tenant.service.UserInfoService;

/**
 * 用户管理
 * @author test
 *
 */
@RestController
@RequestMapping("/v1/users")
public class UserInfoController {

	
	@Resource
	private UserInfoService userInfoService;
	
	/**
	 * 根据ID查询用户
	 * @param id
	 * @return
	 */
	@GetMapping("/details/{id}")
	public UserInfoDto getUserbyId(@PathVariable("id") Integer id) {
		return userInfoService.getUserByid(id);
	}
	
	/**
	 * 根据ID查询用户
	 * @param id
	 * @return
	 */
	@GetMapping("/query/{name}")
	public UserInfoDto getUserbyname(@PathVariable("name") String name) {
		return userInfoService.getUserByname(name);
	}
	
	/**
	 * 创建用户
	 * @param dto
	 * @return
	 */
	@PostMapping("/create")
	public boolean create(@RequestBody UserInfoDto dto) {
		return userInfoService.creaate(dto);
	}
}

 

通过以上步骤就实现Mybatis-plus对多租户的支持。以后就不再需要手动填充租户标识了。

zircloud-tentant: 本项目是采用spring boot 2.x 集成 myabatis-plus 实现多租户

声明:本站部分内容来自互联网,如有版权侵犯或其他问题请与我们联系,我们将立即删除或处理。
▍相关推荐
更多资讯 >>>