Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to configure the dual database driver to connect to the database by Mybatis Plus

2025-04-09 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/01 Report--

This article Xiaobian introduces in detail for you "Mybatis Plus how to configure dual database driver to connect to the database", the content is detailed, the steps are clear, and the details are handled properly. I hope that this "Mybatis Plus how to configure dual database driver to connect to the database" article can help you solve your doubts.

Concrete realization

1. Add the following dependencies to pom.xml:

1.8 1.18.2 3.2.0 1.1.9 UTF-8 UTF-8 org.springframework.boot spring-boot-starter-web mysql mysql-connector-java runtime org.postgresql postgresql runtime com.baomidou mybatis-plus-boot-starter ${mybatis-plus .version} com.baomidou mybatis-plus ${mybatis-plus.version} org.projectlombok lombok ${lombok.version} com.alibaba druid-spring-boot-starter ${druid.version} org.springframework.boot spring-boot-starter-aop

2. Add the following configuration to the yml configuration file:

Server: port: 8080 spring: application: name: xxxx datasource: druid: # mysql data source configuration db1: driver-class-name: com.mysql.jdbc.Driver url: jdbc:mysql://127.0.0.1:3306/db1?useUnicode=true&characterEncoding=UTF-8&useSSL=false username: ${username} password: ${password} initial-size: 5 min-idle: 5 Max-active: 50 # postgresql data source configuration db2: driver-class-name: org.postgresql.Driver url: jdbc:postgresql://127.0.0.1:5432/db2?useUnicode=true&characterEncoding=utf-8 username: ${username} password: ${password} initial-size: 5 min-idle: 5 max-active: 50 # mybatis-plus configuration mybatis-plus: Type-aliases-package: com.dms.gateway.api.entity mapper-locations: classpath:/mapper/*Mapper.xml global-config: db-config: id-type: auto field-strategy: not_empty logic-delete-value: 1 logic-not-delete-value: 0 configuration: map-underscore-to-camel-case: true cache-enabled: false call-setters-on-nulls: true log-impl: org.apache.ibatis.logging.stdout.StdOutImpl

3. Create a new DataSourceEnum enumeration class, as follows:

Public enum DataSourceEnum {DB1 ("db1"), DB2 ("db2"); private String value; DataSourceEnum (String value) {this.value=value;} public String getValue () {return value;}}

4. Create a new DataSourceContextHolder class, as follows:

Public class DataSourceContextHolder {/ / default data source public static final String DEFAULT_DS = DataSourceEnum.DB1.getValue (); private static final ThreadLocal contextHolder = new InheritableThreadLocal (); / * set data source * @ param db * / public static void setDataSource (String db) {contextHolder.set (db) } / * get the current data source * @ return * / public static String getDataSource () {return contextHolder.get ();} / * clear context data * / public static void clear () {contextHolder.remove ();}}

5. Create a new MultipleDataSource class, as follows:

Public class MultipleDataSource extends AbstractRoutingDataSource {@ Override protected Object determineCurrentLookupKey () {return DataSourceContextHolder.getDataSource ();}}

6. Create a new DataSource note, as follows:

@ Target ({ElementType.METHOD,ElementType.TYPE}) @ Retention (RetentionPolicy.RUNTIME) @ Documentedpublic @ interface DataSource {DataSourceEnum value () default DataSourceEnum.DB1;}

7. Create a new aspect at the class and method level, as follows:

@ Component@Slf4j@Aspect@Order (- 6) public class DataSourceClassAspect {@ Before ("@ within (dataSource)") public void doBefore (JoinPoint point, DataSource dataSource) {log.info ("switch to data source [{}]", dataSource.value () .getValue ()); DataSourceContextHolder.setDataSource (dataSource.value () .getValue ()) } @ After ("@ within (dataSource)") public void doAfter (JoinPoint point, DataSource dataSource) {log.info ("Recycling data Source [{}]", dataSource.value () .getValue ()); DataSourceContextHolder.clear () } @ Component@Slf4j@Aspect@Order (- 5) public class DataSourceMethodAspect {@ Before ("@ annotation (dataSource)") public void doBefore (JoinPoint point, DataSource dataSource) {log.info ("switch to data source [{}]", dataSource.value () .getValue ()); DataSourceContextHolder.setDataSource (dataSource.value () .getValue ()) } @ After ("@ annotation (dataSource)") public void doAfter (JoinPoint point, DataSource dataSource) {log.info ("Recycling data Source [{}]", dataSource.value () .getValue ()); DataSourceContextHolder.clear ();}}

8. Create a new multi-data source configuration class, as follows:

@ Configuration@MapperScan ("com.dms.gateway.api.mapper") public class MybatisPlusConfig {/ * * paging plug-in to automatically identify database type * multiple tenants. Please refer to the official website [plug-in extension] * / @ Bean public PaginationInterceptor paginationInterceptor () {PaginationInterceptor paginationInterceptor = new PaginationInterceptor (); return paginationInterceptor } @ Bean (name = "db1") @ ConfigurationProperties (prefix = "spring.datasource.druid.db1") public DataSource db1 () {return DruidDataSourceBuilder.create () .build ();} @ Bean (name = "db2") @ ConfigurationProperties (prefix = "spring.datasource.druid.db2") public DataSource db2 () {return DruidDataSourceBuilder.create () .build () } / * * dynamic data source configuration * @ return * / @ Bean @ Primary public DataSource multipleDataSource (@ Qualifier ("db1") DataSource db1, @ Qualifier ("db2") DataSource db2) {MultipleDataSource multipleDataSource = new MultipleDataSource (); Map

< Object, Object >

TargetDataSources = new HashMap (); targetDataSources.put (DataSourceEnum.DB1.getValue (), db1); targetDataSources.put (DataSourceEnum.DB2.getValue (), db2); / / add data source multipleDataSource.setTargetDataSources (targetDataSources); / / set default data source multipleDataSource.setDefaultTargetDataSource (db1); return multipleDataSource } @ Bean ("sqlSessionFactory") public SqlSessionFactory sqlSessionFactory () throws Exception {MybatisSqlSessionFactoryBean sqlSessionFactory = new MybatisSqlSessionFactoryBean (); sqlSessionFactory.setDataSource (multipleDataSource (db1 (), db2 (); MybatisConfiguration configuration = new MybatisConfiguration (); configuration.setJdbcTypeForNull (JdbcType.NULL); configuration.setMapUnderscoreToCamelCase (true); configuration.setCacheEnabled (false); sqlSessionFactory.setConfiguration (configuration) / / add paging function sqlSessionFactory.setPlugins (paginationInterceptor ()); return sqlSessionFactory.getObject ();}}

Next, you need specific business logic. Add @ DataSource annotation to the class or method in the service layer to specify the data source that the business needs to use, as follows:

@ Service@DataSource (DataSourceEnum.DB2) public class GatewayLogService {@ Autowired private GatewayLogMapper mapper; @ Override public Result pageList (GatewayLogDTO gatewayLogDTO) {LambdaQueryWrapper wrapper = Wrappers.lambdaQuery (); wrapper.like (StringUtils.isNotEmpty (gatewayLogDTO.getPath ()), GatewayLog::getPath, gatewayLogDTO.getPath ()); wrapper.like (StringUtils.isNotEmpty (gatewayLogDTO.getSourceServer ()), GatewayLog::getSourceServer, gatewayLogDTO.getSourceServer ()) Wrapper.like (StringUtils.isNotEmpty (gatewayLogDTO.getTargetServer ()), GatewayLog::getTargetServer, gatewayLogDTO.getTargetServer ()); wrapper.eq (StringUtils.isNotEmpty (gatewayLogDTO.getMethod ()), GatewayLog::getMethod, gatewayLogDTO.getMethod ()); wrapper.like (StringUtils.isNotEmpty (gatewayLogDTO.getRequestBody ()), GatewayLog::getRequestBody, gatewayLogDTO.getRequestBody ()); wrapper.like (StringUtils.isNotEmpty (gatewayLogDTO.getResponse ()), GatewayLog::getResponse, gatewayLogDTO.getResponse ()) Wrapper.orderByDesc (GatewayLog::getId); IPage page = new Page (gatewayLogDTO.getPageNo (), gatewayLogDTO.getPageSize ()); return Result.success (mapper.selectPage (page, wrapper));}}

Start the service and call the relevant APIs. We will see the following information on the console:

It indicates that the data source switching is successful!

After reading this, the article "how to configure Mybatis Plus to connect to the database with dual database drivers" has been introduced. If you want to master the knowledge points of this article, you still need to practice and use it yourself to understand it. If you want to know more about related articles, you are welcome to follow the industry information channel.

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report