首页 课程 师资 教程 报名

MyBatis分库分表实现

  • 2022-06-16 09:48:58
  • 1520次 星辉

MyBatis分库分表如何实现?星辉小编来告诉大家。

首先实现org.apache.ibatis.plugin.Interceptor接口,复写以下三个方法:

实现拦截逻辑的地方,内部要通过invocation.proceed()显式地推进责任链前进,也就是调用下一个拦截器拦截目标方法。

Object intercept(Invocation invocation) throws Throwable;

用当前这个拦截器生成对目标target的代理,实际是通过Plugin.wrap(target,this)来完成的,把目标target和拦截器this传给了包装函数。

Object plugin(Object target);

设置额外的参数,参数配置在拦截器的Properties节点里。

void setProperties(Properties properties);

如果想要拦截所有的sql,在实现类上添加 annotation

@Intercepts({@Signature(type = StatementHandler.class, method = "prepare",
args = {Connection.class})})

注:Mybatis支持对Executor、StatementHandler、PameterHandler和ResultSetHandler进行拦截,也就是说会对这4种对象进行代理。

框架如上,具体实现有两个重要点:

1.表的拆分规则

可以在Mapper对象中加上一个annotation,按以下方式去获取:

String className = id.substring(0, id.lastIndexOf("."));
Class classObj = Class.forName(className);
//根据配置自动生成分表SQL
TableSeg tableSeg = classObj.getAnnotation(TableSeg.class);
TableSeg对象定义:
@Target({ ElementType.TYPE })
@Retention(RetentionPolicy.RUNTIME)
@Inherited
@Documented
public @interface TableSeg {
/**
* 表名
* @return
*/
public String tableName();
/**
* 分表方式,取模,如%5:表示取5余数,
* 如果不设置,直接根据shardBy值分表
* @return
*/
public String shardType();
/**
* 根据什么字段分表
* 多个字段用数学表达表示,如a+b a-b
* @return
*/
public String shardBy();
}

2.sql解析与替换

可以通过以下方法去获取BoundSql,这个对象有关于这个sql的内容

StatementHandler statementHandler = (StatementHandler) invocation.getTarget();
BoundSql boundSql = statementHandler.getBoundSql();

目前看到一些常规做法都是利用string 的replace方案替换sql中的表名,这显然一个埋坑的做法。利用词法分析器才是完美方案,可以使用antlr4,grammar文件可以去github上找到。

选你想看

你适合学Java吗?4大专业测评方法

代码逻辑 吸收能力 技术学习能力 综合素质

先测评确定适合在学习

在线申请免费测试名额
价值1998元实验班免费学
姓名
手机
提交