当前位置: 首页 > article >正文

mysql的分区表

1.SQL表创建

下面以时间范围进行创建(每月一个分区,表中创建了四个月的分区)

创建:

CREATE TABLE test_table (  
    id INT NOT NULL AUTO_INCREMENT,  
    content VARCHAR(255),  
    create_time DATETIME NOT NULL,
   PRIMARY KEY (id, create_time) 
) PARTITION BY RANGE (TO_DAYS(create_time)) (  
    PARTITION p20240601 VALUES LESS THAN (TO_DAYS('2024-06-01')),  
    PARTITION p20240701 VALUES LESS THAN (TO_DAYS('2024-07-01')),  
    PARTITION p20241801 VALUES LESS THAN (TO_DAYS('2024-08-01')),  
    PARTITION p20240901 VALUES LESS THAN (TO_DAYS('2024-09-01'))
);  

查询分区详情:
SELECT *
FROM 
    INFORMATION_SCHEMA.PARTITIONS 
WHERE 
    TABLE_NAME = 'test_table';

2、mapper文件

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper
        PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="*.infrastructure.mapper.TestTableMapper">

    <resultMap id="TestTable" type="*.domain.entity.TestTable">
        <id column="id" property="id" typeHandler="org.apache.ibatis.type.LongTypeHandler"/>
        <result property="content" column="content" jdbcType="VARCHAR"/>
        <result property="createTime" column="create_time" jdbcType="TIMESTAMP"
                typeHandler="org.apache.ibatis.type.LocalDateTimeTypeHandler"/>
    </resultMap>

    <!-- 创建新分区 -->
    <update id="createNewPartition">
        ALTER TABLE TEST_TABLE
            ADD PARTITION (  
                PARTITION ${partitionName} VALUES LESS THAN (TO_DAYS(#{lessThanValue}))
            )
    </update>

    <!-- 删除旧分区 -->
    <update id="dropPartition">
        ALTER TABLE TEST_TABLE
        DROP
        PARTITION
        ${partitionName}
    </update>

    <!--查询是否存在分区-->
    <select id="exitsPartition" resultType="boolean">
        SELECT COUNT(1) > 0
        FROM INFORMATION_SCHEMA.PARTITIONS
        WHERE TABLE_NAME = 'TEST_TABLE'
          AND PARTITION_NAME = #{partitionName}
    </select>

</mapper>

3、service

package *.domain.service;

import *.domain.entity.TestTable;
import *.infrastructure.repo.TestTableRepository;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DataAccessException;
import org.springframework.stereotype.Service;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.YearMonth;
import java.time.format.DateTimeFormatter;
import java.util.Random;

@Service
public class TestTableService {
    @Autowired
    TestTableRepository repository;

	// 插入数据,如果分区不存在,就创建分区,重新插入
    public void insert() {
        TestTable testTable = new TestTable();
        testTable.setContent("test");

        Random random = new Random();
        int i = Math.abs(random.nextInt()) % 365;
        LocalDateTime dateTime = LocalDateTime.now().minusDays(i);
        testTable.setCreateTime(dateTime);

        try {
            repository.getBaseMapper().insert(testTable);
        } catch (DataAccessException e) {
            LocalDate nextMonthFirstDay = YearMonth.from(dateTime).plusMonths(1).atDay(1);
            String lessThanValue = nextMonthFirstDay.format(DateTimeFormatter.ISO_DATE);
            String partitionName = "p" + lessThanValue.replaceAll("-", "");
            // 创建分区时加锁,如果是多节点,需要分布式锁
            synchronized (this) {
                if (!repository.getBaseMapper().exitsPartition(partitionName)) {
                    repository.getBaseMapper().createNewPartition(partitionName, lessThanValue);
                }
            }
            repository.getBaseMapper().insert(testTable);
        }
    }

	// 创建分区
    public void createNewPartition(String partitionName, String lessThanValue) {
        repository.getBaseMapper().createNewPartition(partitionName, lessThanValue);
    }

	// 删除分区
    public void dropPartition(String partitionName) {
        repository.getBaseMapper().dropPartition(partitionName);
    }
}


http://www.kler.cn/news/310378.html

相关文章:

  • 【Finetune】(一)、transformers之BitFit微调
  • ZLMediaKit Windows编译以及使用
  • 浅谈Spring Cloud:认识微服务
  • Flutter问题记录 - 适配Xcode 16和iOS 18
  • 【系统架构设计师-2011年真题】案例分析-答案及详解
  • 优思学院|如何从零开始自己学习六西格玛?
  • 井盖状态检测数据集
  • TCP socket
  • Android 进程间通信
  • 使用llama.cpp 在推理MiniCPM-1.2B模型
  • 24年蓝桥杯及攻防世界赛题-MISC-3
  • 【Redis】Redis 典型应用 - 分布式锁原理与实现
  • 计算机毕业设计 基于SpringBoot框架的网上蛋糕销售系统的设计与实现 Java实战项目 附源码+文档+视频讲解
  • Python编程 - 协程
  • [PICO VR眼镜]眼动追踪串流Unity开发与使用方法,眼动追踪打包报错问题解决(Eye Tracking/手势跟踪)
  • FFmpeg源码:skip_bits、skip_bits1、show_bits函数分析
  • centos远程桌面连接windows
  • iPhone 16系列:熟悉的味道,全新的体验
  • 浅谈Tair缓存的三种存储引擎MDB、LDB、RDB
  • 使用Addressables+SpriteAtlas打包产生冗余
  • Python知识点:详细讲解Python字节码与反编译
  • Elasticsearch 开放推理 API 新增阿里云 AI 搜索支持
  • react 高阶组件
  • 优化数据的抓取规则:减少无效请求
  • 【数学建模】典型相关分析
  • 【RabbitMQ 项目】服务端:数据管理模块之消息管理
  • 大语言模型超参数调优:开启 AI 潜能的钥匙
  • Linux下rpm方式部署mysql(国产化生产环境无联网服务器部署实操)
  • Android开发高频面试题之——Android篇
  • 为什么 ECB 模式不安全