水平分表(Mybatis插件实现)

水平分表(Mybatis插件实现)

tips:(这里可以根据实际业务进行选择,比如每个月数据不是很平均,就可以按照预算数据量来进行分割
例子,按照id mod 100 把表分成100张,然后进行表名+ (id mod 100)取 )

这里为了简单起见,假定月份数据量相差不大
将一张大表按照月份划分
fee_202001,fee_202002,fee_202003…

表中只有三个字段:id,费用金额fee_amt,费用日期fee_date
其中gmt_create,gmt_modified是阿里出的java泰山版表定义的规范
图片.png

需要注意的是插件的注册,只需要在自定义插件上添加@Component,如果是Mybatis单独使用,则需要单独去注册,我这里是配合Spring
核心就在于拦截Executor,这里是只拦截了查询所以是 method添加的query 而且为了简单起见,并没有对缓存做特殊处理,也就是经过这个拦截器执行的开启了缓存也是没有效果的,如果想要生效,则去复写Exector中的另一个方法
图片.png

核心类MyInterceptor

package com.example.interceptor;

import org.apache.ibatis.builder.StaticSqlSource;
import org.apache.ibatis.executor.Executor;
import org.apache.ibatis.mapping.BoundSql;
import org.apache.ibatis.mapping.MappedStatement;
import org.apache.ibatis.mapping.SqlSource;
import org.apache.ibatis.plugin.*;
import org.apache.ibatis.session.ResultHandler;
import org.apache.ibatis.session.RowBounds;
import org.springframework.stereotype.Component;

import java.lang.reflect.Field;
import java.util.Properties;

//Spring项目 添加Component注解 就是插件的注册
@Component
@Intercepts({@Signature(type = Executor.class,method = "query",
        args = {MappedStatement.class, Object.class, RowBounds.class, ResultHandler.class})
})
public class MyInterceptor implements Interceptor {
    @Override
    public Object intercept(Invocation invocation) throws Throwable {
        System.out.println("拦截器执行");

        // 获取参数列表,就是上面注解配置的参数
        Object[] args = invocation.getArgs();
        // 获取ms
        MappedStatement ms= (MappedStatement) args[0];
        // 不是费用查询,继续往下执行
        if(!ms.getId().endsWith("selectByFeeDate")) {
            return invocation.proceed();
        }

        // 获取ms执行参数
        String parameterObject = (String) args[1];
        // 获取ms执行SQL语句
        BoundSql boundSql = ms.getBoundSql(args[1]);

        //获取查询日期年月
        String yearAndMonth = parameterObject.replaceAll("-","").substring(0,6);
        System.out.println("获取查询日期年月==》" + yearAndMonth);


        /**
         * 这里该使用正则匹配,且参数拼接需要校验,以防注入,给上默认值,防止查不到table
         */
        // 替换查询表
        String sql = boundSql.getSql();
        System.out.println("获取sql==》" + sql);

        sql = sql.replace("from fee ", "from fee_" + yearAndMonth + " ");
        System.out.println("change sql:" + sql);


        /**
         * 替换 正要执行的(被我们处理过的sql语句)
         */
        // 自定义sqlSource
        SqlSource sqlSource = new StaticSqlSource(ms.getConfiguration(), sql, boundSql.getParameterMappings());
        // 修改原来的sqlSource
        Field field = MappedStatement.class.getDeclaredField("sqlSource");
        field.setAccessible(true);
        field.set(ms, sqlSource);

        // 执行被拦截方法
        return invocation.proceed();
    }

    @Override
    public Object plugin(Object target) {
        return Plugin.wrap(target,this);
    }

    @Override
    public void setProperties(Properties properties) {

    }
}

测试方法SpringbootMybatisApplicationTests

package com.example;

import com.example.dao.FeeMapper;
import com.example.dao.PersonMapper;
import com.example.entity.Fee;
import com.example.entity.Person;
import org.junit.jupiter.api.Test;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;

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

@SpringBootTest
@MapperScan("com.example.dao")
class SpringbootMybatisApplicationTests {

    @Test
    void contextLoads() {
    }

    @Autowired
    private PersonMapper personMapper;
    @Test
    void testInsert(){
        Person person = new Person();
        person.setId(1);
        List<Integer> list = new ArrayList<>();
        list.add(1);
        list.add(2);
        list.add(3);
        list.add(4);
        person.setCheckBox(list);
        personMapper.insert(person);
    }

    @Autowired
    FeeMapper feeMapper;
    @Test
    void testQueryFeeByFeeDate(){
        String feeDate = "2020-03-01";
        Fee fee = feeMapper.selectByFeeDate(feeDate);
        System.out.println(fee);
    }
}

xml

  <select id="selectByFeeDate" parameterType="string" resultMap="BaseResultMap">
    select <include refid="Base_Column_List" /> from fee where fee_date = #{feeDate}
  </select>

执行结果:
图片.png


版权声明:本文为qq_35368565原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。