基于SpringBoot+Mybatis實(shí)現(xiàn)Mysql分表
基本思路
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)文章希望大家以后多多支持腳本之家!
- Springboot使用MybatisPlus實(shí)現(xiàn)mysql樂觀鎖
- springBoot+mybatis-plus實(shí)現(xiàn)監(jiān)聽mysql數(shù)據(jù)庫(kù)的數(shù)據(jù)增刪改
- SpringBoot集成MyBatisPlus+MySQL的實(shí)現(xiàn)
- SpringBoot+MybatisPlus+Mysql+Sharding-JDBC分庫(kù)分表
- mybatis+springboot中使用mysql的實(shí)例
- SpringBoot+Mybatis-Plus實(shí)現(xiàn)mysql讀寫分離方案的示例代碼
- springboot基于Mybatis mysql實(shí)現(xiàn)讀寫分離
相關(guān)文章
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),本文通過實(shí)例代碼給大家介紹的非常詳細(xì),感興趣的朋友跟隨小編一起看看吧2024-03-03
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)用
這篇文章主要給大家介紹了關(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整合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中的角色,小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,也給大家做個(gè)參考。一起跟隨小編過來看看吧2017-08-08

