From 1bd44a0de7e398214b301ee32e5038bf868291a2 Mon Sep 17 00:00:00 2001 From: farukonfly Date: Wed, 10 Jan 2024 00:46:58 +0800 Subject: [PATCH] =?UTF-8?q?Add:=E8=AE=BE=E7=BD=AE=E5=85=A8=E5=B1=80?= =?UTF-8?q?=E6=96=B9=E8=A8=80?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../mybatisflex/core/dialect/DialectFactory.java | 16 ++++++++++++++++ .../core/mybatis/MapperInvocationHandler.java | 5 +++++ 2 files changed, 21 insertions(+) diff --git a/mybatis-flex-core/src/main/java/com/mybatisflex/core/dialect/DialectFactory.java b/mybatis-flex-core/src/main/java/com/mybatisflex/core/dialect/DialectFactory.java index cfb13564..c46802ff 100644 --- a/mybatis-flex-core/src/main/java/com/mybatisflex/core/dialect/DialectFactory.java +++ b/mybatis-flex-core/src/main/java/com/mybatisflex/core/dialect/DialectFactory.java @@ -18,6 +18,8 @@ package com.mybatisflex.core.dialect; import java.util.EnumMap; import java.util.Map; + +import com.mybatisflex.core.exception.MybatisFlexException; import org.apache.ibatis.util.MapUtil; import com.mybatisflex.core.FlexGlobalConfig; import com.mybatisflex.core.dialect.impl.CommonsDialectImpl; @@ -45,6 +47,7 @@ public class DialectFactory { * 通过设置当前线程的数据库类型,以达到在代码执行时随时切换方言的功能 */ private static final ThreadLocal dbTypeThreadLocal = new ThreadLocal<>(); + private static DbType dbTypeGlobal = null ; /** @@ -75,6 +78,19 @@ public class DialectFactory { return dbTypeThreadLocal.get(); } + public static DbType getGlobalDbType() { + return dbTypeGlobal; + } + + public static void setGlobalDbType(DbType dbType) { + if(dbTypeGlobal == null&&dbType!=null){ + dbTypeGlobal = dbType ; + }else if(dbTypeGlobal != null){ + throw new MybatisFlexException("dbTypeGlobal is only set once"); + }else if(dbType==null){ + throw new MybatisFlexException("dbType can not be null"); + } + } /** * 清除当前线程的 dbType diff --git a/mybatis-flex-core/src/main/java/com/mybatisflex/core/mybatis/MapperInvocationHandler.java b/mybatis-flex-core/src/main/java/com/mybatisflex/core/mybatis/MapperInvocationHandler.java index b61464c8..cad1f7f7 100644 --- a/mybatis-flex-core/src/main/java/com/mybatisflex/core/mybatis/MapperInvocationHandler.java +++ b/mybatis-flex-core/src/main/java/com/mybatisflex/core/mybatis/MapperInvocationHandler.java @@ -76,6 +76,11 @@ public class MapperInvocationHandler implements InvocationHandler { //优先获取用户自己配置的 dbType DbType dbType = DialectFactory.getHintDbType(); + DbType dbTypeGlobal = DialectFactory.getGlobalDbType(); + //当前线程没有设置dbType,但是全局设置了dbTypeGlobal,那么就使用全局的dbTypeGlobal + if(dbTypeGlobal!=null&&dbType==null){ + dbType = dbTypeGlobal ; + } if (dbType == null) { if (dataSourceKey != null && dataSource != null) { dbType = dataSource.getDbType(dataSourceKey);