热爱技术,追求卓越
不断求索,精益求精

【18】MyBatis-Flex多数据源与自动映射策略

从0开始搭建后台管理系统,这是No18。上一篇我们讲到了:引入MyBatis-Flex。这一节,我们来记录下使用MyBatis-Flex的几个细节。

多数据源配置

MyBatis-Flex多数据源配置比较简单:

mybatis-flex:  
  datasource: 
   master: 
    driver-class-name: com.mysql.cj.jdbc.Driver
    url: jdbc:mysql://localhost:3306/yuen?useSSL=false&serverTimezone=Asia/Shanghai&allowPublicKeyRetrieval=true&nullCatalogMeansCurrent=true&rewriteBatchedStatements=true
    username: root
    password: 123456
   test: 
    driver-class-name: com.mysql.cj.jdbc.Driver
    url: jdbc:mysql://localhost:3306/juyou?useSSL=false&serverTimezone=Asia/Shanghai&allowPublicKeyRetrieval=true&nullCatalogMeansCurrent=true&rewriteBatchedStatements=true
    username: root
    password: 123456

查询时,若不指定数据源,则默认使用的是第一个。

注解切换数据源,使用表达式不生效如何解决?

使用注解动态切换数据源,如下:

@UseDataSource("#ds")
@Transactional
@Override
public void importData(List<Data> list, String ds) 

这里的”#ds”表达式,配置中加如下代码即可:

//注入动态数据源取值处理器
DelegatingDataSourceProcessor  dataSourceProcessor = DelegatingDataSourceProcessor.with(
		new SpelExpressionDataSourceProcessor(),
		new ParamIndexDataSourceProcessor()
);
DataSourceManager.setDataSourceProcessor(dataSourceProcessor);

其中ParamIndexDataSourceProcessor,针对简单参数快速取值;SpelExpressionDataSourceProcessor,Spring 模式下 SPEL 表达式取值。

完整配置如下:

package cn.lovecto.yuen.framework.mybatisflex.config;

import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.autoconfigure.AutoConfiguration;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.PropertySource;
import org.springframework.transaction.annotation.EnableTransactionManagement;

import com.mybatisflex.annotation.KeyType;
import com.mybatisflex.core.FlexGlobalConfig;
import com.mybatisflex.core.FlexGlobalConfig.KeyConfig;
import com.mybatisflex.core.datasource.DataSourceManager;
import com.mybatisflex.core.datasource.processor.DelegatingDataSourceProcessor;
import com.mybatisflex.core.datasource.processor.ParamIndexDataSourceProcessor;
import com.mybatisflex.core.keygen.KeyGenerators;
import com.mybatisflex.core.tenant.TenantFactory;
import com.mybatisflex.spring.datasource.processor.SpelExpressionDataSourceProcessor;

import cn.lovecto.yuen.common.domain.BaseEntity;
import cn.lovecto.yuen.common.tenant.YuenTenantProperties;
import cn.lovecto.yuen.common.utils.TenantUtils;
import cn.lovecto.yuen.framework.mybatisflex.listener.FlexInsertListener;
import cn.lovecto.yuen.framework.mybatisflex.listener.FlexUpdateListener;

@AutoConfiguration
@EnableTransactionManagement(proxyTargetClass = true)
@MapperScan("${mybatis-flex.mapperPackage}")
@PropertySource(value = "classpath:common-mybatis.yml")
@EnableConfigurationProperties(YuenTenantProperties.class)
public class YuenMybatisflexAutoConfiguration {
	
	public YuenMybatisflexAutoConfiguration() {
		//全局设置多租户字段,这样就可以省略实体类属性上的 @Column(tenantId = true)注解
		FlexGlobalConfig config =  FlexGlobalConfig.getDefaultConfig();
		config.setTenantColumn("tenant");
		config.setLogicDeleteColumn("deleted");
		config.setNormalValueOfLogicDelete(0);
		config.setDeletedValueOfLogicDelete(1);
		config.setVersionColumn("version");
		config.registerInsertListener(new FlexInsertListener(), BaseEntity.class);
		config.registerUpdateListener(new FlexUpdateListener(), BaseEntity.class);
		KeyConfig keyConfig = new KeyConfig();
		keyConfig.setKeyType(KeyType.Generator);
		keyConfig.setValue(KeyGenerators.snowFlakeId);
		keyConfig.setBefore(true);
		config.setKeyConfig(keyConfig);
		
		//注入动态数据源取值处理器
		DelegatingDataSourceProcessor  dataSourceProcessor = DelegatingDataSourceProcessor.with(
				new SpelExpressionDataSourceProcessor(),
				new ParamIndexDataSourceProcessor()
		);
		DataSourceManager.setDataSourceProcessor(dataSourceProcessor);
	}
	
	/**
	 * 获取租户配置
	 * @return
	 */
	@Bean
    public TenantFactory tenantFactory(){
		
        TenantFactory tenantFactory = new TenantFactory() {
			
			@Override
			public Object[] getTenantIds() {
				Integer tenant = TenantUtils.getTenant();
				if(tenant == null) {
					return null;
				}else {
					return new Object[]{tenant};
				}
			}
		};
        return tenantFactory;
    }

}

Mapper.xml中的查询映射配置

若在Mapper.xml中写了sql语句,要让其自动映射,配置如下:

mybatis-flex:
  configuration:
    # 自动驼峰命名规则(camel case)映射
    mapUnderscoreToCamelCase: true
    # MyBatis 自动映射策略
    # NONE:不启用 PARTIAL:只对非嵌套 resultMap 自动映射 FULL:对所有 resultMap 自动映射
    autoMappingBehavior: FULL
    # MyBatis 自动映射时未知列或未知属性处理策
    # NONE:不做处理 WARNING:打印相关警告 FAILING:抛出异常和详细信息
    autoMappingUnknownColumnBehavior: NONE
    # 更详细的日志输出 会有性能损耗 org.apache.ibatis.logging.stdout.StdOutImpl
    # 关闭日志记录 (可单纯使用 p6spy 分析) org.apache.ibatis.logging.nologging.NoLoggingImpl
    # 默认日志输出 org.apache.ibatis.logging.slf4j.Slf4jImpl
    logImpl: org.apache.ibatis.logging.nologging.NoLoggingImpl
赞(0)
未经允许不得转载:LoveCTO » 【18】MyBatis-Flex多数据源与自动映射策略

评论 抢沙发

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址

热爱技术 追求卓越 精益求精