基于SpringBoot+Mybatis实现Mysql分表

2025-04-07 16:50

本文主要是介绍基于SpringBoot+Mybatis实现Mysql分表,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

《基于SpringBoot+Mybatis实现Mysql分表》这篇文章主要为大家详细介绍了基于SpringBoot+Mybatis实现Mysql分表的相关知识,文中的示例代码讲解详细,感兴趣的小伙伴可...

基本思路

1.根据创建时间字段按年进行分表,比如日志表log可以分为log_2024、log_2025

2.在需要进行插入、android更新操作的地方利用threadlocal将数据表对应的Entity创建时间放入当前的线程中,利用myBATis提供的拦截器在sql执行前进行拦截,将threadlocal中的Entity类取出,根据类上标注的注解获取要操作的表名,再利用创建时间获得最终要操作的实际表名,最后更换sql中的表名让拦截器继续执行

定义注解

定义注解@ShardedTable,将该注解标注在数据表对应的Entity类上,比如User类上

/**
 * 分表注解
 */
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.TYPE)
public @interface ShardedTable {

    // 表名前缀
    String prefix();

}
@ShardedTable(prefix = "user")
@TableName("user")
public class User {

    @TableId(type = IdType.AUTO)
    private Integer id;

    private String name;

    private Integer age;

    public User(String name, Integer age) {
        this.name = name;
        this.age = age;
    }
}

创建ThreadLocal

public class ShardingContext{
    private static final ThreadLocal<ShardingContext> CONTEXT = new ThreadLocal<>();

    private Class<?> entityClass; // 数据表对应的实体类
    private Date date;

    public static void setContext(Class<?> entityClass, Date date) {
        ShardingContext context = new ShardingContext();
        context.entityClass = pythonentityClass;
        context.date = date;
        CONTEXT.set(context);
    }

    public static ShardingContext getContext() {
        return CONTEXT.get();
    }

    public static void clearContext() {
        CONTEXT.remove();
    }

    public Class<?> getEntityClass() {
        return entityClass;
    }

    public Date getDate() {
        return date;
    }
}

创建拦截器

@Component
@Intercepts({@Signature(type = StatementHandler.class, method = "prepare", args = {Connection.class,Integer.class})})
public class ShardingInterceptor implements Interceptor {

    @Autowired
    private ShardingStrategy shardingStrategy;

    @Override
    public Object intercept(Invocation invocation) throws Throwable {
        // 获取原始SQL
        StatementHandler statementHandler = (StatementHandler) invocation.getTarget();
        BoundSql boundSql = statementHandler.getBoundSql();
        String originalSql =  boundSql.getSql();

        // 获取当前操作的实体类
        ShardingContext context = ShardingContext.getContext();
        if (context != null){
            Class<?> epythonntityClass = context.getEntityClass();
            Date date = context.getDate();
            ShardedTable annotation = entityClass.getAnnotation(ShardedTable.class);
            if (annotation != null) {
                // 设置新的sql,替换表名
                String baseTableName = annotation.prefix();
                String actualTableName = shardingStrategy.getTableName(User.class, date);
                String modifiedSql = originalSql.replace(baseTableName, actualTableName);
                setSql(boundSql, modifiedSql);

                // 将数据保存到原表,作为备份
                executeBackupInsert(statementHandler,originalSql);
            }
        }

        return invocation.proceed();
    }

    private void setSql(BoundSql boundSql, String sql) throws Exception {
        Field field = BoundSql.class.getDeclaredField("sql");
        field.setAccessible(true);
        field.set(boundSql, sql);
    }

    // 同时将数据保存到原表,作为备份
    private void executeBackupInsert(StatementHandler statementHandler, String backupSql) throws SQLException {
        Connection connection = null;
        PreparedStatement preparedStatement = null;
        try {
            // 通过反射获取 MappedStatement
            MetaObject metaObject = SystemMetaObject.forObject(statementHandler);
            MappedStatement mappedStatement = (MappedStatement) metaObject.getValue("delegate.mappedStatement");

            connection = mappedStatement.getConfiguration().getEnvironment().getDataSource().getConnection();
            preparedStatement = connection.prepareStatement(backupSql);

            // 设置参数
            ParameterHandler parameterHandler = statementHandler.getParameterHHYHMOandler();
            parameterHandler.setParameters(preparedStatement);

            preparedStatement.executeUpdate();
        } finally {
            if (preparedStatement != null) {
                preparedStatement.close()China编程;
            }
            if (connection != null) {
                connection.close();
            }
        }
    }

    @Override
    public Object plugin(Object target) {
        // 判断是否为StatementHandler类型
        if (target instanceof StatementHandler){
            return Plugin.wrap(target, this);
        }else {
            return target;
        }
    }

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

获取表名

@Component
public class ShardingStrategy {

    public String getTableName(Class<?> entityClass, Date date) {
        ShardedTable annotation = entityClass.getAnnotation(ShardedTable.class);
        if (annotation == null) {
            throw new RuntimeException("实体类必须使用@ShardedTable注解");
        }
        // 获取分表前缀
        String tablePrefix = annotation.prefix();
        if (tablePrefix == null || tablePrefix.isEmpty()) {
            throw new RuntimeException("分表前缀不能为空");
        }
        // 获取当前日期所在的年份
        int year = DateUtil.year(date);
        return tablePrefix + "_" + year;
    }
}

业务处理

在需要进行业务处理的地方,将数据表对应的Entity.class创建时间通过threadlocal放入当前线程中,后面要根据这些信息获取实际要操作的表名

public void insert(ServiceOrderLogEntity serviceOrderLogEntity) {
    ShardingContext.setContext(ServiceOrderLogEntity.class, serviceOrderLogEntity.getTime() == null ? new Date() : serviceOrderLogEntity.getTime());
    
    int result = serviceOrderLogMapper.insert(serviceOrderLogEntity);
    
    ShardingContext.clearContext();
}

到此这篇关于基于SpringBoot+Mybatis实现mysql分表的文章就介绍到这了,更多相关SpringBoot Mysql分表内容请搜索China编程(www.chinasem.cn)以前的文章或继续浏览下面的相关文章希望大家以后多多支持编程China编程(www.chinasem.cn)!

这篇关于基于SpringBoot+Mybatis实现Mysql分表的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/1154111

相关文章

Spring Security常见问题及解决方案

《SpringSecurity常见问题及解决方案》SpringSecurity是Spring生态的安全框架,提供认证、授权及攻击防护,支持JWT、OAuth2集成,适用于保护Spring应用,需配置... 目录Spring Security 简介Spring Security 核心概念1. ​Securit

MySQL 8 中的一个强大功能 JSON_TABLE示例详解

《MySQL8中的一个强大功能JSON_TABLE示例详解》JSON_TABLE是MySQL8中引入的一个强大功能,它允许用户将JSON数据转换为关系表格式,从而可以更方便地在SQL查询中处理J... 目录基本语法示例示例查询解释应用场景不适用场景1. ‌jsON 数据结构过于复杂或动态变化‌2. ‌性能要

Python实现终端清屏的几种方式详解

《Python实现终端清屏的几种方式详解》在使用Python进行终端交互式编程时,我们经常需要清空当前终端屏幕的内容,本文为大家整理了几种常见的实现方法,有需要的小伙伴可以参考下... 目录方法一:使用 `os` 模块调用系统命令方法二:使用 `subprocess` 模块执行命令方法三:打印多个换行符模拟

SpringBoot+EasyPOI轻松实现Excel和Word导出PDF

《SpringBoot+EasyPOI轻松实现Excel和Word导出PDF》在企业级开发中,将Excel和Word文档导出为PDF是常见需求,本文将结合​​EasyPOI和​​Aspose系列工具实... 目录一、环境准备与依赖配置1.1 方案选型1.2 依赖配置(商业库方案)二、Excel 导出 PDF

Python实现MQTT通信的示例代码

《Python实现MQTT通信的示例代码》本文主要介绍了Python实现MQTT通信的示例代码,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一... 目录1. 安装paho-mqtt库‌2. 搭建MQTT代理服务器(Broker)‌‌3. pytho

SpringBoot改造MCP服务器的详细说明(StreamableHTTP 类型)

《SpringBoot改造MCP服务器的详细说明(StreamableHTTP类型)》本文介绍了SpringBoot如何实现MCPStreamableHTTP服务器,并且使用CherryStudio... 目录SpringBoot改造MCP服务器(StreamableHTTP)1 项目说明2 使用说明2.1

MySQL字符串常用函数详解

《MySQL字符串常用函数详解》本文给大家介绍MySQL字符串常用函数,本文结合实例代码给大家介绍的非常详细,对大家学习或工作具有一定的参考借鉴价值,需要的朋友参考下吧... 目录mysql字符串常用函数一、获取二、大小写转换三、拼接四、截取五、比较、反转、替换六、去空白、填充MySQL字符串常用函数一、

spring中的@MapperScan注解属性解析

《spring中的@MapperScan注解属性解析》@MapperScan是Spring集成MyBatis时自动扫描Mapper接口的注解,简化配置并支持多数据源,通过属性控制扫描路径和过滤条件,利... 目录一、核心功能与作用二、注解属性解析三、底层实现原理四、使用场景与最佳实践五、注意事项与常见问题六

Spring的RedisTemplate的json反序列泛型丢失问题解决

《Spring的RedisTemplate的json反序列泛型丢失问题解决》本文主要介绍了SpringRedisTemplate中使用JSON序列化时泛型信息丢失的问题及其提出三种解决方案,可以根据性... 目录背景解决方案方案一方案二方案三总结背景在使用RedisTemplate操作redis时我们针对

Java中Arrays类和Collections类常用方法示例详解

《Java中Arrays类和Collections类常用方法示例详解》本文总结了Java中Arrays和Collections类的常用方法,涵盖数组填充、排序、搜索、复制、列表转换等操作,帮助开发者高... 目录Arrays.fill()相关用法Arrays.toString()Arrays.sort()A