最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

基于SpringBoot+Mybatis實(shí)現(xiàn)Mysql分表

 更新時(shí)間:2025年04月07日 10:34:41   作者:ihgry  
這篇文章主要為大家詳細(xì)介紹了基于SpringBoot+Mybatis實(shí)現(xiàn)Mysql分表的相關(guān)知識(shí),文中的示例代碼講解詳細(xì),感興趣的小伙伴可以跟隨小編一起學(xué)習(xí)一下

基本思路

1.根據(jù)創(chuàng)建時(shí)間字段按年進(jìn)行分表,比如日志表log可以分為log_2024、log_2025

2.在需要進(jìn)行插入、更新操作的地方利用threadlocal將數(shù)據(jù)表對(duì)應(yīng)的Entity創(chuàng)建時(shí)間放入當(dāng)前的線程中,利用mybatis提供的攔截器在sql執(zhí)行前進(jìn)行攔截,將threadlocal中的Entity類取出,根據(jù)類上標(biāo)注的注解獲取要操作的表名,再利用創(chuàng)建時(shí)間獲得最終要操作的實(shí)際表名,最后更換sql中的表名讓攔截器繼續(xù)執(zhí)行

定義注解

定義注解@ShardedTable,將該注解標(biāo)注在數(shù)據(jù)表對(duì)應(yīng)的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;
    }
}

創(chuàng)建ThreadLocal

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

    private Class<?> entityClass; // 數(shù)據(jù)表對(duì)應(yīng)的實(shí)體類
    private Date date;

    public static void setContext(Class<?> entityClass, Date date) {
        ShardingContext context = new ShardingContext();
        context.entityClass = entityClass;
        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;
    }
}

創(chuàng)建攔截器

@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();

        // 獲取當(dāng)前操作的實(shí)體類
        ShardingContext context = ShardingContext.getContext();
        if (context != null){
            Class<?> entityClass = context.getEntityClass();
            Date date = context.getDate();
            ShardedTable annotation = entityClass.getAnnotation(ShardedTable.class);
            if (annotation != null) {
                // 設(shè)置新的sql,替換表名
                String baseTableName = annotation.prefix();
                String actualTableName = shardingStrategy.getTableName(User.class, date);
                String modifiedSql = originalSql.replace(baseTableName, actualTableName);
                setSql(boundSql, modifiedSql);

                // 將數(shù)據(jù)保存到原表,作為備份
                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);
    }

    // 同時(shí)將數(shù)據(jù)保存到原表,作為備份
    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);

            // 設(shè)置參數(shù)
            ParameterHandler parameterHandler = statementHandler.getParameterHandler();
            parameterHandler.setParameters(preparedStatement);

            preparedStatement.executeUpdate();
        } finally {
            if (preparedStatement != null) {
                preparedStatement.close();
            }
            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("實(shí)體類必須使用@ShardedTable注解");
        }
        // 獲取分表前綴
        String tablePrefix = annotation.prefix();
        if (tablePrefix == null || tablePrefix.isEmpty()) {
            throw new RuntimeException("分表前綴不能為空");
        }
        // 獲取當(dāng)前日期所在的年份
        int year = DateUtil.year(date);
        return tablePrefix + "_" + year;
    }
}

業(yè)務(wù)處理

在需要進(jìn)行業(yè)務(wù)處理的地方,將數(shù)據(jù)表對(duì)應(yīng)的Entity.class創(chuàng)建時(shí)間通過threadlocal放入當(dāng)前線程中,后面要根據(jù)這些信息獲取實(shí)際要操作的表名

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

到此這篇關(guān)于基于SpringBoot+Mybatis實(shí)現(xiàn)Mysql分表的文章就介紹到這了,更多相關(guān)SpringBoot Mysql分表內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

相關(guān)文章

  • Mybatis中關(guān)于自定義mapper.xml時(shí),參數(shù)傳遞的方式及寫法

    Mybatis中關(guān)于自定義mapper.xml時(shí),參數(shù)傳遞的方式及寫法

    這篇文章主要介紹了Mybatis中關(guān)于自定義mapper.xml時(shí),參數(shù)傳遞的方式及寫法,具有很好的參考價(jià)值,希望對(duì)大家有所幫助,如有錯(cuò)誤或未考慮完全的地方,望不吝賜教
    2023-12-12
  • springboot swagger 接口文檔分組展示功能實(shí)現(xiàn)

    springboot swagger 接口文檔分組展示功能實(shí)現(xiàn)

    這篇文章主要介紹了springboot swagger 接口文檔分組展示功能實(shí)現(xiàn),本文通過實(shí)例代碼給大家介紹的非常詳細(xì),感興趣的朋友跟隨小編一起看看吧
    2024-03-03
  • 了解JAVA并發(fā)工具常用設(shè)計(jì)套路

    了解JAVA并發(fā)工具常用設(shè)計(jì)套路

    這篇文章主要介紹了了解JAVA并發(fā)工具常用設(shè)計(jì)套路,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,,需要的朋友可以參考下
    2019-06-06
  • IDEA中配置文件模板的添加方法

    IDEA中配置文件模板的添加方法

    這篇文章主要介紹了IDEA中配置文件模板的添加方法,本文給大家介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下
    2021-03-03
  • Spring Boot 中使用 JSON Schema 校驗(yàn)復(fù)雜JSON數(shù)據(jù)的過程

    Spring Boot 中使用 JSON Schema 校驗(yàn)復(fù)雜JSO

    在數(shù)據(jù)交換領(lǐng)域,JSON Schema 以其強(qiáng)大的標(biāo)準(zhǔn)化能力,為定義和規(guī)范 JSON 數(shù)據(jù)的結(jié)構(gòu)與規(guī)則提供了有力支持,下面給大家介紹Spring Boot 中使用 JSON Schema 校驗(yàn)復(fù)雜JSON數(shù)據(jù)的過程,感興趣的朋友跟隨小編一起看看吧
    2024-08-08
  • SpringBoot參數(shù)校驗(yàn)的一些實(shí)戰(zhàn)應(yīng)用

    SpringBoot參數(shù)校驗(yàn)的一些實(shí)戰(zhàn)應(yīng)用

    這篇文章主要給大家介紹了關(guān)于SpringBoot參數(shù)校驗(yàn)的一些實(shí)戰(zhàn)應(yīng)用,包括使用內(nèi)置的參數(shù)校驗(yàn)注解、嵌套對(duì)象校驗(yàn)、分組校驗(yàn)以及自定義校驗(yàn)注解,通過這些方法,可以有效地提高系統(tǒng)的穩(wěn)定性和安全性,需要的朋友可以參考下
    2024-11-11
  • 使用SpringBoot3整合Spring AI實(shí)現(xiàn)具有記憶功能的AI助手

    使用SpringBoot3整合Spring AI實(shí)現(xiàn)具有記憶功能的AI助手

    本文介紹了使用SpringBoot3整合SpringAI和Redis實(shí)現(xiàn)一個(gè)具有記憶功能的AI助手,項(xiàng)目使用Redis作為存儲(chǔ)介質(zhì),支持用戶級(jí)別的會(huì)話隔離和30天的對(duì)話歷史持久化,詳細(xì)介紹了環(huán)境準(zhǔn)備、項(xiàng)目初始化、核心配置、功能實(shí)現(xiàn)及測(cè)試驗(yàn)證步驟,需要的朋友可以參考下
    2026-04-04
  • JNDI在JavaEE中的角色_動(dòng)力節(jié)點(diǎn)Java學(xué)院整理

    JNDI在JavaEE中的角色_動(dòng)力節(jié)點(diǎn)Java學(xué)院整理

    這篇文章主要介紹了JNDI在JavaEE中的角色,小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,也給大家做個(gè)參考。一起跟隨小編過來看看吧
    2017-08-08
  • Java抽象類和抽象方法定義與用法實(shí)例詳解

    Java抽象類和抽象方法定義與用法實(shí)例詳解

    這篇文章主要介紹了Java抽象類和抽象方法定義與用法,結(jié)合實(shí)例形式詳細(xì)分析了Java抽象類和抽象方法相關(guān)原理、定義、使用方法及操作注意事項(xiàng),需要的朋友可以參考下
    2019-11-11
  • 關(guān)于Springboot的日志配置

    關(guān)于Springboot的日志配置

    Spring Boot默認(rèn)使用LogBack日志系統(tǒng),如果不需要更改為其他日志系統(tǒng)如Log4j2等,則無需多余的配置,LogBack默認(rèn)將日志打印到控制臺(tái)上,需要的朋友可以參考下
    2023-05-05

最新評(píng)論

竹山县| 咸阳市| 平顺县| 永靖县| 潮州市| 内黄县| 女性| 健康| 北京市| 巴彦淖尔市| 增城市| 德庆县| 昌宁县| 长宁县| 韶关市| 淅川县| 万载县| 宜阳县| 凯里市| 安乡县| 乌什县| 库尔勒市| 陈巴尔虎旗| 新干县| 门源| 康马县| 太和县| 水城县| 土默特左旗| 龙海市| 遵义县| 五家渠市| 肥乡县| 平安县| 万源市| 安福县| 大渡口区| 土默特左旗| 时尚| 南和县| 大同县|