Spring Boot 集成mybatis-plus 的多租户插件

5 篇文章 0 订阅
1 篇文章 0 订阅

MyBatis-Plus(简称 MP)是一个 MyBatis 的增强工具,在 MyBatis 的基础上只做增强不做改变,为简化开发、提高效率而生。

具体介绍查看官方文档,我也不是很熟。

官方文档2.x:https://baomidou.gitee.io/mybatis-plus-doc/#/quick-start

最新官方文档3.x:https://mp.baomidou.com/guide/quick-start.html

 

调整 SqlSessionFactory 为 MyBatis-Plus 的 SqlSessionFactory

<bean id="sqlSessionFactory" class="com.baomidou.mybatisplus.extension.spring.MybatisSqlSessionFactoryBean">
    <property name="dataSource" ref="dataSource"/>
</bean>

防止有些功能使用时报错,分页插件功能就会。
 

遇到的问题:

1.依赖引入(注意版本的兼容性)

特别说明:MybatisMybatis-Spring依赖请勿加入项目配置,以免引起版本冲突!!!Mybatis-Plus会自动帮你维护!

如果是项目后期引入Mybatis-Plus需要注意自己项目本身的MybatisMybatis-Spring版本从而引入适合的mybatis-plus 版本,我是用的就不是最新的。

<dependency>
	<groupId>com.baomidou</groupId>
	<artifactId>mybatis-plus-boot-starter</artifactId>
	<version>3.0.4</version>
</dependency>
<dependency>
	<groupId>com.baomidou</groupId>
	<artifactId>mybatis-plus</artifactId>
	<version>3.0.4</version>
</dependency>
<dependency>
	<groupId>com.baomidou</groupId>
	<artifactId>mybatis-plus-generator</artifactId>
	<version>3.0.4</version>
</dependency>

可在官方文档上跳转到GitHub上查看不同版本的Mybatis-Plus 对应使用的mybatis版本

2.添加过滤配置文件

package com.biomatch.qadm.util.interceptor;

import java.util.ArrayList;
import java.util.List;
import java.util.Properties;

import org.apache.ibatis.plugin.Interceptor;
import org.apache.ibatis.plugin.Invocation;
import org.apache.shiro.SecurityUtils;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.transaction.annotation.EnableTransactionManagement;

import com.baomidou.mybatisplus.core.parser.ISqlParser;
import com.baomidou.mybatisplus.extension.plugins.PaginationInterceptor;
import com.baomidou.mybatisplus.extension.plugins.PerformanceInterceptor;
import com.baomidou.mybatisplus.extension.plugins.tenant.TenantHandler;
import com.baomidou.mybatisplus.extension.plugins.tenant.TenantSqlParser;
import com.biomatch.qadm.bean.vo.Operator;
import com.biomatch.qadm.util.Constants;

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

/**
 * @since 2019-07-23
 */
@Configuration
@MapperScan("com.biomatch.qadm.service.impl.dao.impl.*")
@EnableTransactionManagement
public class MybatisPlusConfig {

	/*
    // 从配置获取
    @Value("{}")
	private boolean tenantEnabled;*/
    /**
     * 多租户属于 SQL 解析部分,依赖 MP 分页插件
     */
    @Bean("paginationInterceptor")
    public Interceptor paginationInterceptor() {
        // 可实现是否启用多租户功能
    	/*if(!tenantEnabled){
    		return dummyInterceptor();
    	}*/
    	
    	
    	PaginationInterceptor paginationInterceptor = new PaginationInterceptor();
        /* 
         * 【测试多租户】 SQL 解析处理拦截器<br>
         * 这里固定写成住户 1 实际情况你可以从cookie读取,因此数据看不到 【 麻花藤 】 这条记录( 注意观察 SQL )<br>
         */
        //System.out.println("MybatisPlusConfig000");
        List<ISqlParser> sqlParserList = new ArrayList<>();
        TenantSqlParser tenantSqlParser = new TenantSqlParser();
        tenantSqlParser.setTenantHandler(new TenantHandler() {

            @Override
            public Expression getTenantId() {
            	//System.out.println("MybatisPlusConfig-getTenantId");
                return new LongValue(1L);
            }

            @Override
            public String getTenantIdColumn() {
            	//System.out.println("MybatisPlusConfig-getTenantIdColumn");
                return "tenant_id";
            }

            @Override
            public boolean doTableFilter(String tableName) {
            	//System.out.println("MybatisPlusConfig-doTableFilter");
                // 这里可以判断是否过滤表
                /*if ("user".equals(tableName)) {
                    return true;
                }*/
                return false;
            }
        });

        sqlParserList.add(tenantSqlParser);
        paginationInterceptor.setSqlParserList(sqlParserList);
        /*paginationInterceptor.setSqlParserFilter(new ISqlParserFilter() {
            @Override
            public boolean doFilter(MetaObject metaObject) {
                   // getMappedStatement 方法不知道版本才实现,作用无法也就是获取sql的执行路径和SQL语句,可自己实现获取即可
                // MappedStatement ms = PluginUtils.getMappedStatement(metaObject);
                   MappedStatement ms = (MappedStatement) metaObject.getValue("delegate.mappedStatement");
                // 过滤自定义查询此时无租户信息约束【 麻花藤 】出现
                if ("com.baomidou.springboot.mapper.UserMapper.selectListBySQL".equals(ms.getId())) {
                    return true;
                }
                return false;
            }
        });*/
        return paginationInterceptor;
	}
    


    /**
     * 性能分析拦截器,不建议生产使用
     * 用来观察 SQL 执行情况及执行时长
     */
    @Bean("performanceInterceptor")
    public Interceptor performanceInterceptor(){
        return new PerformanceInterceptor();
    }
    
    public Interceptor dummyInterceptor(){
        return new Interceptor(){

			@Override
			public Object intercept(Invocation invocation) throws Throwable {
				return invocation.proceed();
			}

			@Override
			public Object plugin(Object target) {
				return target;
			}

			@Override
			public void setProperties(Properties properties) {
				
			}
        	
        };
    }
    
}

3.在jdbc配置时添加mybatis-plus分页插件

<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
    <property name="dataSource" ref="dataSource" />
	<property name="typeAliasesPackage" value="com.biomatch.qadm.bean.entity" />
	<property name="mapperLocations" value="classpath:/mybatis/*.xml" />
	<!-- 添加各种插件 -->
	<property name="plugins">
		<list>
            <!-- 添加MP插件 -->
			<ref bean="paginationInterceptor" />
			<ref bean="performanceInterceptor"/>
		</list>
	</property> 
</bean>

配置完成:

最后在执行SQL时会在where条件添加上tenant_id='1'

insert 时 也会添加 字段tenant_id

 

SQL拦截器需要用到的类

1.获取方法名

StatementHandler statementHandler = (StatementHandler) invocation.getTarget();  
MetaObject metaStatementHandler = SystemMetaObject.forObject(statementHandler);  
MappedStatement mappedStatement=(MappedStatement) metaStatementHandler.getValue("delegate.mappedStatement");
String selectId=mappedStatement.getId();
// selectId 的值为:com.baomidou.springboot.mapper.UserMapper.selectListBySQL

2.获取sql

BoundSql boundSql = (BoundSql) metaStatementHandler.getValue("delegate.boundSql");  
// 分页参数作为参数对象parameterObject的一个属性
String sql = boundSql.getSql();
Common co=(Common)(boundSql.getParameterObject());

注意:

1.mybatis 编写sql时,一些符号使用转移字符,否则 mybatis-plus 无法识别,会报符号异常

原符号         替换符号
1.<            &lt;
2.<=           &lt;=
3.>            &gt;
4.>=           &gt;=
5.&            &amp;
6.'           &apos;
7."           &quot;
8.!=          &lt;&gt;

2.这个框架好像不识别双引号,使用单引号代替双引号,反正SQL识别时单引号也可以表示字符串

  • 1
    点赞
  • 12
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
以下是一些可能包括在大熊猫国家公园门户网站 Mybatis-plus 技术博客中的内容: 1. Mybatis-plus 简介:介绍 Mybatis-plus 的功能、优势等。 2. Mybatis-plus 基本使用:包括如何集成 Mybatis-plus、如何进行 CRUD 操作、如何使用条件构造器、如何使用自定义 SQL 等。 3. Mybatis-plus 高级查询:介绍 Mybatis-plus 的各种高级查询方式,如 Lambda 表达式、QueryWrapper、UpdateWrapper、EntityWrapper 等。 4. Mybatis-plus 分页:介绍 Mybatis-plus 的分页查询方式、分页插件的使用、自定义分页插件的实现等。 5. Mybatis-plus 乐观锁:介绍 Mybatis-plus 的乐观锁功能、如何使用乐观锁、乐观锁的实现原理等。 6. Mybatis-plus 多租户:介绍 Mybatis-plus多租户功能、如何使用多租户多租户的实现原理等。 7. Mybatis-plus 性能优化:介绍 Mybatis-plus 的性能优化技巧、如何使用分片表、如何使用缓存等。 8. Mybatis-plusSpring Boot 集成:介绍如何将 Mybatis-plus 集成Spring Boot 项目中、如何配置 Mybatis-plus、如何使用 Mybatis-plus Starter 等。 9. Mybatis-plus 与其他技术集成:介绍如何将 Mybatis-plus 与其他技术集成,如 Redis、Elasticsearch、ShardingSphere 等。 此外,Mybatis-plus 技术博客也可以包括一些实践经验、案例分析、问题解决过程等内容,以帮助读者更好地理解和使用 Mybatis-plus。在大熊猫国家公园门户网站 Mybatis-plus 技术博客中,可以结合实际项目经验,讲解如何使用 Mybatis-plus 来构建高性能、可扩展的数据访问层。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值