This commit is contained in:
2025-12-07 12:30:54 +08:00
parent b7b31d9f86
commit 2ac9d4c85f
20 changed files with 2409 additions and 54 deletions

81
pom.xml
View File

@ -43,61 +43,92 @@
</scm>
<properties>
<java.version>25</java.version>
<java.version>17</java.version>
<spring-boot.version>4.0.0</spring-boot.version>
<mybatis-spring.version>4.0.0</mybatis-spring.version>
<mybatis-flex.version>1.11.4</mybatis-flex.version>
<mybatis-freemarker.version>1.3.1</mybatis-freemarker.version>
<mybatis-velocity.version>2.3.0</mybatis-velocity.version>
<mybatis-thymeleaf.version>1.1.0</mybatis-thymeleaf.version>
<HikariCP.version>7.0.2</HikariCP.version>
<seata.version>2.0.0</seata.version>
</properties>
<dependencies>
<!-- Spring Boot -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-webmvc</artifactId>
<artifactId>spring-boot-configuration-processor</artifactId>
<version>${spring-boot.version}</version>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-configuration-processor</artifactId>
<artifactId>spring-boot-autoconfigure</artifactId>
<version>${spring-boot.version}</version>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-autoconfigure-processor</artifactId>
<version>${spring-boot.version}</version>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-jdbc</artifactId>
<version>${spring-boot.version}</version>
<optional>true</optional>
</dependency>
<!-- MyBatis -->
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<groupId>org.mybatis</groupId>
<artifactId>mybatis-spring</artifactId>
<version>${mybatis-spring.version}</version>
</dependency>
<!-- JDBC Drivers -->
<dependency>
<groupId>com.zaxxer</groupId>
<artifactId>HikariCP</artifactId>
<version>${HikariCP.version}</version>
<groupId>com.mybatis-flex</groupId>
<artifactId>mybatis-flex-spring</artifactId>
<version>${mybatis-flex.version}</version>
</dependency>
<dependency>
<groupId>org.postgresql</groupId>
<artifactId>postgresql</artifactId>
<version>42.7.8</version>
</dependency>
<!-- Testing -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-webmvc-test</artifactId>
<version>${spring-boot.version}</version>
<scope>test</scope>
<groupId>org.mybatis.scripting</groupId>
<artifactId>mybatis-freemarker</artifactId>
<version>${mybatis-freemarker.version}</version>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter-test</artifactId>
<version>${mybatis-spring.version}</version>
<scope>test</scope>
<groupId>org.mybatis.scripting</groupId>
<artifactId>mybatis-velocity</artifactId>
<version>${mybatis-velocity.version}</version>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.mybatis.scripting</groupId>
<artifactId>mybatis-thymeleaf</artifactId>
<version>${mybatis-thymeleaf.version}</version>
<optional>true</optional>
</dependency>
<!-- JDBC Drivers & DataSources -->
<dependency>
<groupId>io.seata</groupId>
<artifactId>seata-rm-datasource</artifactId>
<version>${seata.version}</version>
<scope>compile</scope>
<optional>true</optional>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<configuration>
<source>${java.version}</source>
<target>${java.version}</target>
<encoding>UTF-8</encoding>
</configuration>
</plugin>
</plugins>
</build>

View File

@ -0,0 +1,69 @@
/*
* Copyright (c) 2022-2025, Mybatis-Flex (fuhai999@gmail.com).
* <p>
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* <p>
* http://www.apache.org/licenses/LICENSE-2.0
* <p>
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.mybatisflex.spring.boot;
import org.springframework.boot.autoconfigure.condition.ConditionOutcome;
import org.springframework.boot.autoconfigure.condition.SpringBootCondition;
import org.springframework.context.annotation.ConditionContext;
import org.springframework.context.annotation.Conditional;
import org.springframework.core.Ordered;
import org.springframework.core.annotation.Order;
import org.springframework.core.env.*;
import org.springframework.core.type.AnnotatedTypeMetadata;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import java.util.Iterator;
/**
* <p>判断是否有 MyBatis-Flex 的多数据源配置。
* <p>如果配置文件中有 MyBatis-Flex 的多数据源配置,就加载 MyBatis-Flex 多数据源自动配置类。
*
* @author michael
*/
@Target({ElementType.TYPE, ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
@Conditional(ConditionalOnMybatisFlexDatasource.OnMybatisFlexDataSourceCondition.class)
public @interface ConditionalOnMybatisFlexDatasource {
@Order(Ordered.HIGHEST_PRECEDENCE)
class OnMybatisFlexDataSourceCondition extends SpringBootCondition {
@Override
public ConditionOutcome getMatchOutcome(ConditionContext context, AnnotatedTypeMetadata metadata) {
Environment env = context.getEnvironment();
if (env instanceof AbstractEnvironment) {
MutablePropertySources propertySources = ((AbstractEnvironment) env).getPropertySources();
Iterator<PropertySource<?>> it = propertySources.stream().iterator();
while (it.hasNext()) {
PropertySource<?> ps = it.next();
if (ps instanceof EnumerablePropertySource) {
for (String propertyName : ((EnumerablePropertySource<?>) ps).getPropertyNames()) {
if (propertyName.startsWith("mybatis-flex.datasource.")) {
return ConditionOutcome.match();
}
}
}
}
}
return ConditionOutcome.noMatch("'mybatis-flex.datasource' is necessary.");
}
}
}

View File

@ -0,0 +1,34 @@
/*
* Copyright (c) 2022-2025, Mybatis-Flex (fuhai999@gmail.com).
* <p>
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* <p>
* http://www.apache.org/licenses/LICENSE-2.0
* <p>
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.mybatisflex.spring.boot;
import com.mybatisflex.core.mybatis.FlexConfiguration;
/**
* 为 {@link FlexConfiguration} 做自定义的配置支持。
* @author michael
*/
@FunctionalInterface
public interface ConfigurationCustomizer {
/**
* 自定义配置 {@link FlexConfiguration}。
*
* @param configuration MyBatis Flex Configuration
*/
void customize(FlexConfiguration configuration);
}

View File

@ -0,0 +1,74 @@
/*
* Copyright (c) 2022-2025, Mybatis-Flex (fuhai999@gmail.com).
* <p>
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* <p>
* http://www.apache.org/licenses/LICENSE-2.0
* <p>
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.mybatisflex.spring.boot;
import com.mybatisflex.core.row.Db;
import com.mybatisflex.spring.FlexTransactionManager;
import org.jspecify.annotations.NonNull;
import org.springframework.beans.factory.config.BeanDefinition;
import org.springframework.boot.autoconfigure.AutoConfigureAfter;
import org.springframework.boot.autoconfigure.AutoConfigureBefore;
import org.springframework.boot.autoconfigure.AutoConfigureOrder;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.jdbc.autoconfigure.DataSourceTransactionManagerAutoConfiguration;
import org.springframework.boot.transaction.autoconfigure.TransactionAutoConfiguration;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Role;
import org.springframework.core.Ordered;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.TransactionManager;
import org.springframework.transaction.annotation.TransactionManagementConfigurer;
/**
* MyBatis-Flex 事务自动配置。
*
* @author michael
*/
@ConditionalOnClass(
value = Db.class,
name = {
"org.springframework.boot.transaction.autoconfigure.TransactionAutoConfiguration",
"org.springframework.boot.jdbc.autoconfigure.DataSourceTransactionManagerAutoConfiguration",
}
)
@Role(BeanDefinition.ROLE_INFRASTRUCTURE)
@ConditionalOnMissingBean(TransactionManager.class)
@Configuration(proxyBeanMethods = false)
@AutoConfigureOrder(Ordered.HIGHEST_PRECEDENCE)
@AutoConfigureAfter({MybatisFlexAutoConfiguration.class})
@AutoConfigureBefore(value = {TransactionAutoConfiguration.class, DataSourceTransactionManagerAutoConfiguration.class})
public class FlexTransactionAutoConfiguration implements TransactionManagementConfigurer {
/**
* 这里使用 final 修饰属性是因为:<br>
* <p>
* 1、调用 {@link #annotationDrivenTransactionManager} 方法会返回 TransactionManager 对象<br>
* 2、{@code @Bean} 注入又会返回 TransactionManager 对象<br>
* <p>
* 需要保证两个对象的一致性。
*/
private final FlexTransactionManager flexTransactionManager = new FlexTransactionManager();
@NonNull
@Override
@Bean(name = "transactionManager")
public PlatformTransactionManager annotationDrivenTransactionManager() {
return flexTransactionManager;
}
}

View File

@ -0,0 +1,158 @@
/*
* Copyright (c) 2022-2024, Mybatis-Flex (fuhai999@gmail.com).
* <p>
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* <p>
* http://www.apache.org/licenses/LICENSE-2.0
* <p>
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.mybatisflex.spring.boot;
import com.mybatisflex.core.datasource.DataSourceBuilder;
import com.mybatisflex.core.datasource.DataSourceDecipher;
import com.mybatisflex.core.datasource.DataSourceManager;
import com.mybatisflex.core.datasource.FlexDataSource;
import com.mybatisflex.core.dialect.DbType;
import com.mybatisflex.core.dialect.DbTypeUtil;
import com.mybatisflex.core.exception.FlexExceptions;
import com.mybatisflex.core.util.MapUtil;
import com.mybatisflex.spring.boot.MybatisFlexProperties.SeataConfig;
import com.mybatisflex.spring.datasource.DataSourceAdvice;
import io.seata.rm.datasource.DataSourceProxy;
import io.seata.rm.datasource.xa.DataSourceProxyXA;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.springframework.beans.factory.ObjectProvider;
import org.springframework.beans.factory.config.BeanDefinition;
import org.springframework.boot.autoconfigure.AutoConfigureBefore;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.boot.jdbc.autoconfigure.DataSourceAutoConfiguration;
import org.springframework.boot.jdbc.autoconfigure.DataSourceTransactionManagerAutoConfiguration;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Role;
import javax.sql.DataSource;
import java.util.Map;
import java.util.Optional;
/**
* MyBatis-Flex 多数据源的配置支持。
*
* @author michael
* @author 王帅
*/
@ConditionalOnMybatisFlexDatasource()
@Configuration(proxyBeanMethods = false)
@EnableConfigurationProperties(MybatisFlexProperties.class)
@ConditionalOnClass(
value = {SqlSessionFactory.class, SqlSessionFactoryBean.class},
name = {
"org.springframework.boot.jdbc.autoconfigure.DataSourceAutoConfiguration",
"org.springframework.boot.jdbc.autoconfigure.DataSourceTransactionManagerAutoConfiguration",
}
)
@AutoConfigureBefore(value = {DataSourceAutoConfiguration.class, DataSourceTransactionManagerAutoConfiguration.class}
, name = {"com.alibaba.druid.spring.boot.autoconfigure.DruidDataSourceAutoConfigure",
"com.alibaba.druid.spring.boot4.autoconfigure.DruidDataSourceAutoConfigure"})
public class MultiDataSourceAutoConfiguration {
private final String master;
private final Map<String, Map<String, String>> dataSourceProperties;
private final SeataConfig seataConfig;
// 数据源解密器
protected final DataSourceDecipher dataSourceDecipher;
public MultiDataSourceAutoConfiguration(MybatisFlexProperties properties
, ObjectProvider<DataSourceDecipher> dataSourceDecipherProvider
) {
dataSourceProperties = properties.getDatasource();
dataSourceDecipher = dataSourceDecipherProvider.getIfAvailable();
seataConfig = properties.getSeataConfig();
master = properties.getDefaultDatasourceKey();
}
@Bean
@ConditionalOnMissingBean
public DataSource dataSource() {
FlexDataSource flexDataSource = null;
if (dataSourceProperties != null && !dataSourceProperties.isEmpty()) {
if (dataSourceDecipher != null) {
DataSourceManager.setDecipher(dataSourceDecipher);
}
if (master != null) {
Map<String, String> map = dataSourceProperties.remove(master);
if (map != null) {
// 这里创建master时flexDataSource一定是null
flexDataSource = addDataSource(MapUtil.entry(master, map), null);
} else {
throw FlexExceptions.wrap("没有找到默认数据源 \"%s\" 对应的配置,请检查您的多数据源配置。", master);
}
}
for (Map.Entry<String, Map<String, String>> entry : dataSourceProperties.entrySet()) {
flexDataSource = addDataSource(entry, flexDataSource);
}
}
return flexDataSource;
}
private FlexDataSource addDataSource(Map.Entry<String, Map<String, String>> entry, FlexDataSource flexDataSource) {
DataSource dataSource = new DataSourceBuilder(entry.getValue()).build();
DataSourceManager.decryptDataSource(dataSource);
// 数据库类型
DbType dbType = null;
if (seataConfig != null && seataConfig.isEnable()) {
if (seataConfig.getSeataMode() == MybatisFlexProperties.SeataMode.XA) {
DataSourceProxyXA sourceProxyXa = new DataSourceProxyXA(dataSource);
dbType = DbType.findByName(sourceProxyXa.getDbType());
dataSource = sourceProxyXa;
} else {
DataSourceProxy dataSourceProxy = new DataSourceProxy(dataSource);
dbType = DbType.findByName(dataSourceProxy.getDbType());
dataSource = dataSourceProxy;
}
}
// 如果没有构建成功dbType需要自解析
final DataSource lambdaInnerDataSource = dataSource;
dbType = Optional.ofNullable(dbType).orElseGet(() -> DbTypeUtil.getDbType(lambdaInnerDataSource));
if (flexDataSource == null) {
flexDataSource = new FlexDataSource(entry.getKey(), dataSource, dbType, false);
} else {
flexDataSource.addDataSource(entry.getKey(), dataSource, dbType, false);
}
return flexDataSource;
}
/**
* {@link com.mybatisflex.annotation.UseDataSource} 注解切换数据源切面。
*/
@Bean
@ConditionalOnMissingBean
@Role(BeanDefinition.ROLE_INFRASTRUCTURE)
public DataSourceAdvice dataSourceAdvice() {
return new DataSourceAdvice();
}
}

View File

@ -0,0 +1,48 @@
/*
* Copyright (c) 2022-2025, Mybatis-Flex (fuhai999@gmail.com).
* <p>
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* <p>
* http://www.apache.org/licenses/LICENSE-2.0
* <p>
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.mybatisflex.spring.boot;
import com.mybatisflex.core.FlexGlobalConfig;
/**
* <p>MyBatis-Flex 配置。
*
* <p>一般可以用于去初始化:
*
* <ul>
* <li>FlexGlobalConfig 的全局配置
* <li>自定义主键生成器
* <li>多租户配置
* <li>动态表名配置
* <li>逻辑删除处理器配置
* <li>自定义脱敏规则
* <li>SQL 审计配置
* <li>SQL 打印配置
* <li>数据源解密器配置
* <li>自定义数据方言配置
* <li>...
* </ul>
*/
public interface MyBatisFlexCustomizer {
/**
* 自定义 MyBatis-Flex 配置。
*
* @param globalConfig 全局配置
*/
void customize(FlexGlobalConfig globalConfig);
}

View File

@ -0,0 +1,69 @@
/*
* Copyright (c) 2022-2025, Mybatis-Flex (fuhai999@gmail.com).
* <p>
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* <p>
* http://www.apache.org/licenses/LICENSE-2.0
* <p>
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.mybatisflex.spring.boot;
import com.mybatisflex.core.audit.AuditManager;
import com.mybatisflex.core.audit.MessageFactory;
import com.mybatisflex.core.audit.MessageReporter;
import com.mybatisflex.core.audit.http.HttpMessageReporter;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.ObjectProvider;
import org.springframework.boot.autoconfigure.AutoConfigureAfter;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Configuration;
/**
* MyBatis-Flex-Admin 自动配置。
*
* @author 王帅
* @since 2023-07-01
*/
@Configuration(proxyBeanMethods = false)
@AutoConfigureAfter(MybatisFlexAutoConfiguration.class)
@EnableConfigurationProperties(MybatisFlexProperties.class)
@ConditionalOnProperty(prefix = "mybatis-flex.admin-config", name = "enable", havingValue = "true")
public class MybatisFlexAdminAutoConfiguration implements InitializingBean {
private final MessageFactory messageFactory;
private final MybatisFlexProperties properties;
private final HttpMessageReporter.JSONFormatter jsonFormatter;
public MybatisFlexAdminAutoConfiguration(ObjectProvider<MessageFactory> messageFactory,
ObjectProvider<HttpMessageReporter.JSONFormatter> jsonFormatter,
MybatisFlexProperties properties) {
this.properties = properties;
this.jsonFormatter = jsonFormatter.getIfAvailable();
this.messageFactory = messageFactory.getIfAvailable();
}
@Override
public void afterPropertiesSet() {
AuditManager.setAuditEnable(true);
if (messageFactory != null) {
AuditManager.setMessageFactory(messageFactory);
}
MybatisFlexProperties.AdminConfig adminConfig = properties.getAdminConfig();
MessageReporter messageReporter = new HttpMessageReporter(
adminConfig.getEndpoint(),
adminConfig.getSecretKey(),
jsonFormatter
);
AuditManager.setMessageReporter(messageReporter);
}
}

View File

@ -0,0 +1,427 @@
/*
* Copyright 2015-2022 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.mybatisflex.spring.boot;
import com.mybatisflex.core.FlexGlobalConfig;
import com.mybatisflex.core.datasource.DataSourceDecipher;
import com.mybatisflex.core.datasource.DataSourceManager;
import com.mybatisflex.core.logicdelete.LogicDeleteManager;
import com.mybatisflex.core.logicdelete.LogicDeleteProcessor;
import com.mybatisflex.core.mybatis.FlexConfiguration;
import com.mybatisflex.core.table.DynamicSchemaProcessor;
import com.mybatisflex.core.table.DynamicTableProcessor;
import com.mybatisflex.core.table.TableManager;
import com.mybatisflex.core.tenant.TenantFactory;
import com.mybatisflex.core.tenant.TenantManager;
import com.mybatisflex.spring.FlexSqlSessionFactoryBean;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.mapping.DatabaseIdProvider;
import org.apache.ibatis.plugin.Interceptor;
import org.apache.ibatis.scripting.LanguageDriver;
import org.apache.ibatis.session.ExecutorType;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.type.TypeHandler;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.SqlSessionTemplate;
import org.mybatis.spring.mapper.MapperFactoryBean;
import org.mybatis.spring.mapper.MapperScannerConfigurer;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanWrapper;
import org.springframework.beans.BeanWrapperImpl;
import org.springframework.beans.factory.*;
import org.springframework.beans.factory.config.BeanDefinition;
import org.springframework.beans.factory.support.BeanDefinitionBuilder;
import org.springframework.beans.factory.support.BeanDefinitionRegistry;
import org.springframework.boot.autoconfigure.AutoConfigurationPackages;
import org.springframework.boot.autoconfigure.AutoConfigureAfter;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnSingleCandidate;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.boot.jdbc.autoconfigure.DataSourceAutoConfiguration;
import org.springframework.context.EnvironmentAware;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;
import org.springframework.context.annotation.ImportBeanDefinitionRegistrar;
import org.springframework.core.env.Environment;
import org.springframework.core.io.Resource;
import org.springframework.core.io.ResourceLoader;
import org.springframework.core.type.AnnotationMetadata;
import org.springframework.util.Assert;
import org.springframework.util.CollectionUtils;
import org.springframework.util.ObjectUtils;
import org.springframework.util.StringUtils;
import javax.sql.DataSource;
import java.beans.PropertyDescriptor;
import java.util.List;
import java.util.Optional;
import java.util.Set;
import java.util.stream.Collectors;
import java.util.stream.Stream;
/**
* Mybatis-Flex 的核心配置。
* <p>
* 参考 <a href="https://github.com/mybatis/spring-boot-starter/blob/master/mybatis-spring-boot-autoconfigure/src/main/java/org/mybatis/spring/boot/autoconfigure/MybatisAutoConfiguration.java">
* MybatisAutoConfiguration.java</a>
* <p>
* 为 Mybatis-Flex 开启自动配置功能,主要修改以下几个方面:
* <p>
* 1、替换配置为 mybatis-flex 的配置前缀<br>
* 2、修改 SqlSessionFactory 为 FlexSqlSessionFactoryBean<br>
* 3、修改 Configuration 为 FlexConfiguration<br>
*
* @author Eddú Meléndez
* @author Josh Long
* @author Kazuki Shimizu
* @author Eduardo Macarrón
* @author michael
* @author 王帅
*/
@Configuration(proxyBeanMethods = false)
@ConditionalOnClass(
value = {SqlSessionFactory.class, SqlSessionFactoryBean.class},
name = {
"org.springframework.boot.jdbc.autoconfigure.DataSourceAutoConfiguration",
}
)
@ConditionalOnSingleCandidate(DataSource.class)
@EnableConfigurationProperties(MybatisFlexProperties.class)
@AutoConfigureAfter({DataSourceAutoConfiguration.class, MybatisLanguageDriverAutoConfiguration.class})
public class MybatisFlexAutoConfiguration implements InitializingBean {
protected static final Logger logger = LoggerFactory.getLogger(MybatisFlexAutoConfiguration.class);
protected final MybatisFlexProperties properties;
protected final Interceptor[] interceptors;
protected final TypeHandler[] typeHandlers;
protected final LanguageDriver[] languageDrivers;
protected final ResourceLoader resourceLoader;
protected final DatabaseIdProvider databaseIdProvider;
protected final List<ConfigurationCustomizer> configurationCustomizers;
protected final List<SqlSessionFactoryBeanCustomizer> sqlSessionFactoryBeanCustomizers;
//数据源解密器
protected final DataSourceDecipher dataSourceDecipher;
//动态表名
protected final DynamicTableProcessor dynamicTableProcessor;
//动态 schema 处理器
protected final DynamicSchemaProcessor dynamicSchemaProcessor;
//多租户
protected final TenantFactory tenantFactory;
//自定义逻辑删除处理器
protected final LogicDeleteProcessor logicDeleteProcessor;
//初始化监听
protected final List<MyBatisFlexCustomizer> mybatisFlexCustomizers;
public MybatisFlexAutoConfiguration(MybatisFlexProperties properties, ObjectProvider<Interceptor[]> interceptorsProvider,
ObjectProvider<TypeHandler[]> typeHandlersProvider, ObjectProvider<LanguageDriver[]> languageDriversProvider,
ResourceLoader resourceLoader, ObjectProvider<DatabaseIdProvider> databaseIdProvider,
ObjectProvider<List<ConfigurationCustomizer>> configurationCustomizersProvider,
ObjectProvider<List<SqlSessionFactoryBeanCustomizer>> sqlSessionFactoryBeanCustomizers,
ObjectProvider<DataSourceDecipher> dataSourceDecipherProvider,
ObjectProvider<DynamicTableProcessor> dynamicTableProcessorProvider,
ObjectProvider<DynamicSchemaProcessor> dynamicSchemaProcessorProvider,
ObjectProvider<TenantFactory> tenantFactoryProvider,
ObjectProvider<LogicDeleteProcessor> logicDeleteProcessorProvider,
ObjectProvider<MyBatisFlexCustomizer> mybatisFlexCustomizerProviders
) {
this.properties = properties;
this.interceptors = interceptorsProvider.getIfAvailable();
this.typeHandlers = typeHandlersProvider.getIfAvailable();
this.languageDrivers = languageDriversProvider.getIfAvailable();
this.resourceLoader = resourceLoader;
this.databaseIdProvider = databaseIdProvider.getIfAvailable();
this.configurationCustomizers = configurationCustomizersProvider.getIfAvailable();
this.sqlSessionFactoryBeanCustomizers = sqlSessionFactoryBeanCustomizers.getIfAvailable();
//数据源解密器
this.dataSourceDecipher = dataSourceDecipherProvider.getIfAvailable();
//动态表名
this.dynamicTableProcessor = dynamicTableProcessorProvider.getIfAvailable();
//动态 schema 处理器
this.dynamicSchemaProcessor = dynamicSchemaProcessorProvider.getIfAvailable();
//多租户
this.tenantFactory = tenantFactoryProvider.getIfAvailable();
//逻辑删除处理器
this.logicDeleteProcessor = logicDeleteProcessorProvider.getIfAvailable();
//初始化监听器
this.mybatisFlexCustomizers = mybatisFlexCustomizerProviders.orderedStream().collect(Collectors.toList());
}
@Override
public void afterPropertiesSet() {
// 检测 MyBatis 原生配置文件是否存在
checkConfigFileExists();
// 添加 MyBatis-Flex 全局配置
if (properties.getGlobalConfig() != null) {
properties.getGlobalConfig().applyTo(FlexGlobalConfig.getDefaultConfig());
}
//数据源解密器
if (dataSourceDecipher != null) {
DataSourceManager.setDecipher(dataSourceDecipher);
}
// 动态表名配置
if (dynamicTableProcessor != null) {
TableManager.setDynamicTableProcessor(dynamicTableProcessor);
}
// 动态 schema 处理器配置
if (dynamicSchemaProcessor != null) {
TableManager.setDynamicSchemaProcessor(dynamicSchemaProcessor);
}
//多租户
if (tenantFactory != null) {
TenantManager.setTenantFactory(tenantFactory);
}
//逻辑删除处理器
if (logicDeleteProcessor != null) {
LogicDeleteManager.setProcessor(logicDeleteProcessor);
}
//初始化监听器
if (mybatisFlexCustomizers != null) {
mybatisFlexCustomizers.forEach(myBatisFlexCustomizer -> myBatisFlexCustomizer.customize(FlexGlobalConfig.getDefaultConfig()));
}
}
private void checkConfigFileExists() {
if (this.properties.isCheckConfigLocation() && StringUtils.hasText(this.properties.getConfigLocation())) {
Resource resource = this.resourceLoader.getResource(this.properties.getConfigLocation());
Assert.state(resource.exists(),
"Cannot find config location: " + resource + " (please add config file or check your Mybatis configuration)");
}
}
@Bean
@ConditionalOnMissingBean
public SqlSessionFactory sqlSessionFactory(DataSource dataSource) throws Exception {
SqlSessionFactoryBean factory = new FlexSqlSessionFactoryBean();
factory.setDataSource(dataSource);
if (properties.getConfiguration() == null || properties.getConfiguration().getVfsImpl() == null) {
factory.setVfs(SpringBootVFS.class);
}
if (StringUtils.hasText(this.properties.getConfigLocation())) {
factory.setConfigLocation(this.resourceLoader.getResource(this.properties.getConfigLocation()));
}
applyConfiguration(factory);
if (this.properties.getConfigurationProperties() != null) {
factory.setConfigurationProperties(this.properties.getConfigurationProperties());
}
if (!ObjectUtils.isEmpty(this.interceptors)) {
factory.setPlugins(this.interceptors);
}
if (this.databaseIdProvider != null) {
factory.setDatabaseIdProvider(this.databaseIdProvider);
}
if (StringUtils.hasLength(this.properties.getTypeAliasesPackage())) {
factory.setTypeAliasesPackage(this.properties.getTypeAliasesPackage());
}
if (this.properties.getTypeAliasesSuperType() != null) {
factory.setTypeAliasesSuperType(this.properties.getTypeAliasesSuperType());
}
if (StringUtils.hasLength(this.properties.getTypeHandlersPackage())) {
factory.setTypeHandlersPackage(this.properties.getTypeHandlersPackage());
}
if (!ObjectUtils.isEmpty(this.typeHandlers)) {
factory.setTypeHandlers(this.typeHandlers);
}
Resource[] mapperLocations = this.properties.resolveMapperLocations();
if (!ObjectUtils.isEmpty(mapperLocations)) {
factory.setMapperLocations(mapperLocations);
}
Set<String> factoryPropertyNames = Stream
.of(new BeanWrapperImpl(SqlSessionFactoryBean.class).getPropertyDescriptors()).map(PropertyDescriptor::getName)
.collect(Collectors.toSet());
Class<? extends LanguageDriver> defaultLanguageDriver = this.properties.getDefaultScriptingLanguageDriver();
if (factoryPropertyNames.contains("scriptingLanguageDrivers") && !ObjectUtils.isEmpty(this.languageDrivers)) {
// Need to mybatis-spring 2.0.2+
factory.setScriptingLanguageDrivers(this.languageDrivers);
if (defaultLanguageDriver == null && this.languageDrivers.length == 1) {
defaultLanguageDriver = this.languageDrivers[0].getClass();
}
}
if (factoryPropertyNames.contains("defaultScriptingLanguageDriver")) {
// Need to mybatis-spring 2.0.2+
factory.setDefaultScriptingLanguageDriver(defaultLanguageDriver);
}
applySqlSessionFactoryBeanCustomizers(factory);
return factory.getObject();
}
protected void applyConfiguration(SqlSessionFactoryBean factory) {
MybatisFlexProperties.CoreConfiguration coreConfiguration = this.properties.getConfiguration();
FlexConfiguration configuration = null;
if (coreConfiguration != null || !StringUtils.hasText(this.properties.getConfigLocation())) {
configuration = new FlexConfiguration();
}
if (configuration != null && coreConfiguration != null) {
coreConfiguration.applyTo(configuration);
}
if (configuration != null && !CollectionUtils.isEmpty(this.configurationCustomizers)) {
for (ConfigurationCustomizer customizer : this.configurationCustomizers) {
customizer.customize(configuration);
}
}
factory.setConfiguration(configuration);
}
protected void applySqlSessionFactoryBeanCustomizers(SqlSessionFactoryBean factory) {
if (!CollectionUtils.isEmpty(this.sqlSessionFactoryBeanCustomizers)) {
for (SqlSessionFactoryBeanCustomizer customizer : this.sqlSessionFactoryBeanCustomizers) {
customizer.customize(factory);
}
}
}
@Bean
@ConditionalOnMissingBean
public SqlSessionTemplate sqlSessionTemplate(SqlSessionFactory sqlSessionFactory) {
ExecutorType executorType = this.properties.getExecutorType();
if (executorType != null) {
return new SqlSessionTemplate(sqlSessionFactory, executorType);
} else {
return new SqlSessionTemplate(sqlSessionFactory);
}
}
/**
* This will just scan the same base package as Spring Boot does. If you want more power, you can explicitly use
* {@link org.mybatis.spring.annotation.MapperScan} but this will get typed mappers working correctly, out-of-the-box,
* similar to using Spring Data JPA repositories.
*/
public static class AutoConfiguredMapperScannerRegistrar
implements BeanFactoryAware, EnvironmentAware, ImportBeanDefinitionRegistrar {
private BeanFactory beanFactory;
private Environment environment;
@Override
public void registerBeanDefinitions(AnnotationMetadata importingClassMetadata, BeanDefinitionRegistry registry) {
if (!AutoConfigurationPackages.has(this.beanFactory)) {
logger.debug("Could not determine auto-configuration package, automatic mapper scanning disabled.");
return;
}
logger.debug("Searching for mappers annotated with @Mapper");
List<String> packages = AutoConfigurationPackages.get(this.beanFactory);
if (logger.isDebugEnabled()) {
packages.forEach(pkg -> logger.debug("Using auto-configuration base package '{}'", pkg));
}
BeanDefinitionBuilder builder = BeanDefinitionBuilder.genericBeanDefinition(MapperScannerConfigurer.class);
builder.addPropertyValue("processPropertyPlaceHolders", true);
builder.addPropertyValue("annotationClass", Mapper.class);
builder.addPropertyValue("basePackage", StringUtils.collectionToCommaDelimitedString(packages));
BeanWrapper beanWrapper = new BeanWrapperImpl(MapperScannerConfigurer.class);
Set<String> propertyNames = Stream.of(beanWrapper.getPropertyDescriptors()).map(PropertyDescriptor::getName)
.collect(Collectors.toSet());
if (propertyNames.contains("lazyInitialization")) {
// Need to mybatis-spring 2.0.2+
builder.addPropertyValue("lazyInitialization", "${mybatis.lazy-initialization:false}");
}
if (propertyNames.contains("defaultScope")) {
// Need to mybatis-spring 2.0.6+
builder.addPropertyValue("defaultScope", "${mybatis.mapper-default-scope:}");
}
// for spring-native
boolean injectSqlSession = environment.getProperty("mybatis.inject-sql-session-on-mapper-scan", Boolean.class,
Boolean.TRUE);
if (injectSqlSession && this.beanFactory instanceof ListableBeanFactory) {
ListableBeanFactory listableBeanFactory = (ListableBeanFactory) this.beanFactory;
Optional<String> sqlSessionTemplateBeanName = Optional
.ofNullable(getBeanNameForType(SqlSessionTemplate.class, listableBeanFactory));
Optional<String> sqlSessionFactoryBeanName = Optional
.ofNullable(getBeanNameForType(SqlSessionFactory.class, listableBeanFactory));
if (sqlSessionTemplateBeanName.isPresent() || !sqlSessionFactoryBeanName.isPresent()) {
builder.addPropertyValue("sqlSessionTemplateBeanName",
sqlSessionTemplateBeanName.orElse("sqlSessionTemplate"));
} else {
builder.addPropertyValue("sqlSessionFactoryBeanName", sqlSessionFactoryBeanName.get());
}
}
builder.setRole(BeanDefinition.ROLE_INFRASTRUCTURE);
registry.registerBeanDefinition(MapperScannerConfigurer.class.getName(), builder.getBeanDefinition());
}
@Override
public void setBeanFactory(BeanFactory beanFactory) {
this.beanFactory = beanFactory;
}
@Override
public void setEnvironment(Environment environment) {
this.environment = environment;
}
private String getBeanNameForType(Class<?> type, ListableBeanFactory factory) {
String[] beanNames = factory.getBeanNamesForType(type);
return beanNames.length > 0 ? beanNames[0] : null;
}
}
/**
* If mapper registering configuration or mapper scanning configuration not present, this configuration allow to scan
* mappers based on the same component-scanning path as Spring Boot itself.
*/
@org.springframework.context.annotation.Configuration(proxyBeanMethods = false)
@Import(AutoConfiguredMapperScannerRegistrar.class)
@ConditionalOnMissingBean({MapperFactoryBean.class, MapperScannerConfigurer.class})
public static class MapperScannerRegistrarNotFoundConfiguration implements InitializingBean {
@Override
public void afterPropertiesSet() {
logger.debug(
"Not found configuration for registering mapper bean using @MapperScan, MapperFactoryBean and MapperScannerConfigurer.");
}
}
}

View File

@ -0,0 +1,39 @@
/*
* Copyright 2015-2022 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.mybatisflex.spring.boot;
import org.mybatis.spring.SqlSessionTemplate;
import org.springframework.boot.sql.init.dependency.AbstractBeansOfTypeDependsOnDatabaseInitializationDetector;
import org.springframework.boot.sql.init.dependency.DependsOnDatabaseInitializationDetector;
import java.util.Collections;
import java.util.Set;
/**
* 参考:<a href="https://github.com/mybatis/spring-boot-starter/blob/master/mybatis-spring-boot-autoconfigure/src/main/java/org/mybatis/spring/boot/autoconfigure/MybatisDependsOnDatabaseInitializationDetector.java">...</a>
* {@link DependsOnDatabaseInitializationDetector} for Mybatis-Flex.
*
* @author Eddú Meléndez
*/
class MybatisFlexDependsOnDatabaseInitializationDetector
extends AbstractBeansOfTypeDependsOnDatabaseInitializationDetector {
@Override
protected Set<Class<?>> getDependsOnDatabaseInitializationBeanTypes() {
return Collections.singleton(SqlSessionTemplate.class);
}
}

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,158 @@
/*
* Copyright 2015-2022 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.mybatisflex.spring.boot;
import org.apache.ibatis.scripting.LanguageDriver;
import org.mybatis.scripting.freemarker.FreeMarkerLanguageDriver;
import org.mybatis.scripting.freemarker.FreeMarkerLanguageDriverConfig;
import org.mybatis.scripting.thymeleaf.ThymeleafLanguageDriver;
import org.mybatis.scripting.thymeleaf.ThymeleafLanguageDriverConfig;
import org.mybatis.scripting.velocity.VelocityLanguageDriver;
import org.mybatis.scripting.velocity.VelocityLanguageDriverConfig;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingClass;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
/**
* 脚本语言驱动的自动配置,平常一般项目用不到,只为了同步 MyBatis 自带的 MybatisLanguageDriverAutoConfiguration。
* 参考:<a href="https://github.com/mybatis/spring-boot-starter/blob/master/mybatis-spring-boot-autoconfigure/src/main/java/org/mybatis/spring/boot/autoconfigure/MybatisLanguageDriverAutoConfiguration.java">...</a>
* @author Kazuki Shimizu
* @author michael
*/
@Configuration(proxyBeanMethods = false)
@ConditionalOnClass(LanguageDriver.class)
public class MybatisLanguageDriverAutoConfiguration {
private static final String CONFIGURATION_PROPERTY_PREFIX = "mybatis-flex.scripting-language-driver";
/**
* Configuration class for mybatis-freemarker 1.1.x or under.
*/
@Configuration(proxyBeanMethods = false)
@ConditionalOnClass(FreeMarkerLanguageDriver.class)
@ConditionalOnMissingClass("org.mybatis.scripting.freemarker.FreeMarkerLanguageDriverConfig")
public static class LegacyFreeMarkerConfiguration {
@Bean
@ConditionalOnMissingBean
FreeMarkerLanguageDriver freeMarkerLanguageDriver() {
return new FreeMarkerLanguageDriver();
}
}
/**
* Configuration class for mybatis-freemarker 1.2.x or above.
*/
@Configuration(proxyBeanMethods = false)
@ConditionalOnClass({FreeMarkerLanguageDriver.class, FreeMarkerLanguageDriverConfig.class})
public static class FreeMarkerConfiguration {
@Bean
@ConditionalOnMissingBean
FreeMarkerLanguageDriver freeMarkerLanguageDriver(FreeMarkerLanguageDriverConfig config) {
return new FreeMarkerLanguageDriver(config);
}
@Bean
@ConditionalOnMissingBean
@ConfigurationProperties(CONFIGURATION_PROPERTY_PREFIX + ".freemarker")
public FreeMarkerLanguageDriverConfig freeMarkerLanguageDriverConfig() {
return FreeMarkerLanguageDriverConfig.newInstance();
}
}
/**
* Configuration class for mybatis-velocity 2.0 or under.
*/
@Configuration(proxyBeanMethods = false)
@ConditionalOnClass(org.mybatis.scripting.velocity.Driver.class)
@ConditionalOnMissingClass("org.mybatis.scripting.velocity.VelocityLanguageDriverConfig")
@SuppressWarnings("deprecation")
public static class LegacyVelocityConfiguration {
@Bean
@ConditionalOnMissingBean
org.mybatis.scripting.velocity.Driver velocityLanguageDriver() {
return new org.mybatis.scripting.velocity.Driver();
}
}
/**
* Configuration class for mybatis-velocity 2.1.x or above.
*/
@Configuration(proxyBeanMethods = false)
@ConditionalOnClass({VelocityLanguageDriver.class, VelocityLanguageDriverConfig.class})
public static class VelocityConfiguration {
@Bean
@ConditionalOnMissingBean
VelocityLanguageDriver velocityLanguageDriver(VelocityLanguageDriverConfig config) {
return new VelocityLanguageDriver(config);
}
@Bean
@ConditionalOnMissingBean
@ConfigurationProperties(CONFIGURATION_PROPERTY_PREFIX + ".velocity")
public VelocityLanguageDriverConfig velocityLanguageDriverConfig() {
return VelocityLanguageDriverConfig.newInstance();
}
}
@Configuration(proxyBeanMethods = false)
@ConditionalOnClass(ThymeleafLanguageDriver.class)
public static class ThymeleafConfiguration {
@Bean
@ConditionalOnMissingBean
ThymeleafLanguageDriver thymeleafLanguageDriver(ThymeleafLanguageDriverConfig config) {
return new ThymeleafLanguageDriver(config);
}
@Bean
@ConditionalOnMissingBean
@ConfigurationProperties(CONFIGURATION_PROPERTY_PREFIX + ".thymeleaf")
public ThymeleafLanguageDriverConfig thymeleafLanguageDriverConfig() {
return ThymeleafLanguageDriverConfig.newInstance();
}
// This class provides to avoid the https://github.com/spring-projects/spring-boot/issues/21626 as workaround.
@SuppressWarnings("unused")
private static class MetadataThymeleafLanguageDriverConfig extends ThymeleafLanguageDriverConfig {
@ConfigurationProperties(CONFIGURATION_PROPERTY_PREFIX + ".thymeleaf.dialect")
@Override
public DialectConfig getDialect() {
return super.getDialect();
}
@ConfigurationProperties(CONFIGURATION_PROPERTY_PREFIX + ".thymeleaf.template-file")
@Override
public TemplateFileConfig getTemplateFile() {
return super.getTemplateFile();
}
}
}
}

View File

@ -0,0 +1,93 @@
/*
* Copyright 2015-2023 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.mybatisflex.spring.boot;
import org.apache.ibatis.io.VFS;
import org.springframework.core.io.Resource;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.core.io.support.ResourcePatternResolver;
import java.io.IOException;
import java.io.UncheckedIOException;
import java.net.URL;
import java.net.URLDecoder;
import java.nio.charset.Charset;
import java.text.Normalizer;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;
/**
* MyBatis 的 VFS 支持。
* 参考:<a href="https://github.com/mybatis/spring-boot-starter/blob/master/mybatis-spring-boot-autoconfigure/src/main/java/org/mybatis/spring/boot/autoconfigure/SpringBootVFS.java">...</a>
* @author Hans Westerbeek
* @author Eddú Meléndez
* @author Kazuki Shimizu
* @author Michael
*/
public class SpringBootVFS extends VFS {
private static Charset urlDecodingCharset;
static {
setUrlDecodingCharset(Charset.defaultCharset());
}
private final ResourcePatternResolver resourceResolver;
public SpringBootVFS() {
this.resourceResolver = new PathMatchingResourcePatternResolver(getClass().getClassLoader());
}
/**
* Set the charset for decoding an encoded URL string.
* <p>
* Default is system default charset.
* </p>
*
* @param charset the charset for decoding an encoded URL string
* @since 2.3.0
*/
public static void setUrlDecodingCharset(Charset charset) {
urlDecodingCharset = charset;
}
private static String preserveSubpackageName(final String baseUrlString, final Resource resource,
final String rootPath) {
try {
return rootPath + (rootPath.endsWith("/") ? "" : "/") + Normalizer
.normalize(URLDecoder.decode(resource.getURL().toString(), urlDecodingCharset.name()), Normalizer.Form.NFC)
.substring(baseUrlString.length());
} catch (IOException e) {
throw new UncheckedIOException(e);
}
}
@Override
public boolean isValid() {
return true;
}
@Override
protected List<String> list(URL url, String path) throws IOException {
String urlString = URLDecoder.decode(url.toString(), urlDecodingCharset.name());
String baseUrlString = urlString.endsWith("/") ? urlString : urlString.concat("/");
Resource[] resources = resourceResolver.getResources(baseUrlString + "**/*.class");
return Stream.of(resources).map(resource -> preserveSubpackageName(baseUrlString, resource, path))
.collect(Collectors.toList());
}
}

View File

@ -0,0 +1,37 @@
/*
* Copyright 2015-2022 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.mybatisflex.spring.boot;
import org.mybatis.spring.SqlSessionFactoryBean;
/**
* 参考:<a href="https://github.com/mybatis/spring-boot-starter/blob/master/mybatis-spring-boot-autoconfigure/src/main/java/org/mybatis/spring/boot/autoconfigure/SqlSessionFactoryBeanCustomizer.java">...</a>
*
* 为 FlexSqlSessionFactoryBean 做自定义的配置支持。
*
* @see com.mybatisflex.spring.FlexSqlSessionFactoryBean
*/
@FunctionalInterface
public interface SqlSessionFactoryBeanCustomizer {
/**
* 自定义 {@link SqlSessionFactoryBean}。
*
* @param factoryBean FlexSqlSessionFactoryBean
*/
void customize(SqlSessionFactoryBean factoryBean);
}

View File

@ -0,0 +1,20 @@
/*
* Copyright (c) 2022-2025, Mybatis-Flex (fuhai999@gmail.com).
* <p>
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* <p>
* http://www.apache.org/licenses/LICENSE-2.0
* <p>
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/**
* MyBatis-Flex Spring Boot 支持
*/
package com.mybatisflex.spring.boot;

View File

@ -1,4 +0,0 @@
/**
* MyBatis-Flex Spring Boot 支持
*/
package com.mybatisflex.spring.boot.v4;

View File

@ -1,12 +0,0 @@
package day.gitlab.mybatisflex;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class MyBatisFlexApplication {
public static void main(String[] args) {
SpringApplication.run(MyBatisFlexApplication.class, args);
}
}

View File

@ -0,0 +1,91 @@
{
"properties": [
{
"defaultValue": false,
"name": "mybatis-flex.lazy-initialization",
"description": "Set whether enable lazy initialization for mapper bean.",
"type": "java.lang.Boolean"
},
{
"defaultValue": "",
"name": "mybatis-flex.mapper-default-scope",
"description": "A default scope for mapper bean that scanned by auto-configure.",
"type": "java.lang.String"
},
{
"defaultValue": true,
"name": "mybatis-flex.inject-sql-session-on-mapper-scan",
"description": "Set whether inject a SqlSessionTemplate or SqlSessionFactory bean (If you want to back to the behavior of 2.2.1 or before, specify false). If you use together with spring-native, should be set true.",
"type": "java.lang.Boolean"
},
{
"name": "mybatis-flex.scripting-language-driver.velocity.userdirective",
"deprecation": {
"level": "error",
"reason": "The 'userdirective' is deprecated since Velocity 2.x. This property defined for keeping backward compatibility with older velocity version.",
"replacement": "mybatis-flex.scripting-language-driver.velocity.velocity-settings.runtime.custom_directives"
}
},
{
"defaultValue": true,
"name": "mybatis-flex.datasource",
"description": "多数据源配置",
"type": "java.util.Map<java.lang.String,com.mybatisflex.spring.boot.DataSourceProperty>"
},
{
"defaultValue": 0,
"name": "mybatis-flex.global-config.normal-value-of-logic-delete",
"description": "逻辑删除未删除值标记",
"type": "java.lang.Object"
},
{
"defaultValue": 1,
"name": "mybatis-flex.global-config.deleted-value-of-logic-delete",
"description": "逻辑删除已删除值标记",
"type": "java.lang.Object"
},
{
"defaultValue": 10,
"name": "mybatis-flex.global-config.default-page-size",
"description": "默认的分页查询时的每页数据量",
"type": "java.lang.Integer"
},
{
"defaultValue": 2,
"name": "mybatis-flex.global-config.default-relation-query-depth",
"description": "默认的 Relation 注解查询深度",
"type": "java.lang.Integer"
},
{
"name": "mybatis-flex.global-config.key-config.value",
"description": "使用的 ID 生成器名称 或者 Sequence 执行的 SQL 内容",
"type": "java.lang.String"
},
{
"defaultValue": true,
"name": "mybatis-flex.global-config.key-config.before",
"description": "是否在数据插入之前执行,只在非自增上配置有效",
"type": "java.lang.Boolean"
},
{
"name": "mybatis-flex.global-config.key-config.key-type",
"description": "ID 生成策略",
"type": "com.mybatisflex.annotation.KeyType"
},
{
"name": "mybatis-flex.global-config.logic-delete-column",
"description": "全局默认逻辑删除字段",
"type": "java.lang.String"
},
{
"name": "mybatis-flex.global-config.tenant-column",
"description": "全局默认多租户字段",
"type": "java.lang.String"
},
{
"name": "mybatis-flex.global-config.version-column",
"description": "全局默认逻辑乐观锁字段",
"type": "java.lang.String"
}
]
}

View File

@ -0,0 +1,9 @@
# Depends On Database Initialization Detectors
org.springframework.boot.sql.init.dependency.DependsOnDatabaseInitializationDetector=\
com.mybatisflex.spring.boot.MybatisFlexDependsOnDatabaseInitializationDetector
org.springframework.boot.autoconfigure.EnableAutoConfiguration=\
com.mybatisflex.spring.boot.FlexTransactionAutoConfiguration,\
com.mybatisflex.spring.boot.MultiDataSourceAutoConfiguration,\
com.mybatisflex.spring.boot.MybatisFlexAutoConfiguration,\
com.mybatisflex.spring.boot.MybatisFlexAdminAutoConfiguration,\
com.mybatisflex.spring.boot.MybatisLanguageDriverAutoConfiguration

View File

@ -0,0 +1,5 @@
com.mybatisflex.spring.boot.FlexTransactionAutoConfiguration
com.mybatisflex.spring.boot.MultiDataSourceAutoConfiguration
com.mybatisflex.spring.boot.MybatisFlexAutoConfiguration
com.mybatisflex.spring.boot.MybatisFlexAdminAutoConfiguration
com.mybatisflex.spring.boot.MybatisLanguageDriverAutoConfiguration

View File

@ -1,13 +0,0 @@
server:
port: 8080
servlet:
context-path: /
spring:
application:
name: mybatis-flex-spring-boot4-starter
datasource:
type: com.zaxxer.hikari.HikariDataSource
driver-class-name: org.postgresql.Driver
url: jdbc:postgresql://110.42.60.129:10002/postgres
username: postgres
password: postgres