In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-03-31 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Internet Technology >
Share
Shulou(Shulou.com)06/02 Report--
Today, I will talk to you about how to use mybatis to configure multiple data sources in springboot. Many people may not know much about it. In order to make you understand better, the editor has summarized the following for you. I hope you can get something according to this article.
I. how to create a bean after a successful start of the project
Pom.xml
Com.alibaba druid-spring-boot-starter 1.1.10 com.ojdbc ojdbc 10.2.0.1 system ${project.basedir} / src/main/lib/ojdbc14-10.2.0.1.0.jar mysql mysql-connector-java 5.1.38
Application.properties
# oracle database spring.datasource.master.url=jdbc:oracle:thin:@localhost:1521:testspring.datasource.master.username=oraclespring.datasource.master.password=123456spring.datasource.master.driverClassName=oracle.jdbc.OracleDriverspring.datasource.master.initialSize=5spring.datasource.master.maxActive=15spring.datasource.master.minIdle=5spring.datasource.master.poolPreparedStatements=truespring.datasource.master.validationQuery=SELECT 1 FROM DUAL# configuration executes multiple sql for example: batch processing # corresponding error: sql injection violation Multi-statement not allowspring.datasource.master.wall.multiStatementAllow=true# configuration executes special sql, such as sql server's create temporary table (declare) statement # corresponding error: sql injection violation Class com.alibaba.druid.sql.ast.statement.SQLDeclareStatement not allowspring.datasource.master.wall.noneBaseStatementAllow=true#mysql database spring.datasource.slave.url=jdbc:mysql://localhost:3306/test?characterEncoding=utf8spring.datasource.slave.username=mysqlspring.datasource.slave.password=123456spring.datasource.slave.driverClassName=com.mysql.cj.jdbc.Driverspring.datasource.slave.initialSize=5spring.datasource.slave.maxActive=15spring.datasource.slave.minIdle=5spring.datasource.slave.poolPreparedStatements=truespring.datasource.slave.validationQuery=SELECT databases is configured to execute multiple sql such as: error corresponding to batch processing #: sql injection violation Multi-statement not allowspring.datasource.master.wall.multiStatementAllow=true# configuration executes special sql, such as sql server's create temporary table (declare) statement # corresponding error: sql injection violation, class com.alibaba.druid.sql.ast.statement.SQLDeclareStatement not allowspring.datasource.master.wall.noneBaseStatementAllow=true
MasterDataSourceConfig.java
Note: the Primary annotation represents the data source as the main data source
Package com.core.dataSource;import com.alibaba.druid.spring.boot.autoconfigure.DruidDataSourceBuilder;import org.apache.ibatis.session.SqlSessionFactory;import org.mybatis.spring.SqlSessionFactoryBean;import org.mybatis.spring.SqlSessionTemplate;import org.mybatis.spring.annotation.MapperScan;import org.springframework.beans.factory.annotation.Qualifier;import org.springframework.boot.context.properties.ConfigurationProperties;import org.springframework.context.annotation.Bean;import org.springframework.context.annotation.Configuration;import org.springframework.context.annotation.Primary Import org.springframework.core.io.support.PathMatchingResourcePatternResolver;import org.springframework.jdbc.datasource.DataSourceTransactionManager;import javax.sql.DataSource / * oracle data configuration * / @ Configuration// configure the mapper file directory, scan @ MapperScan (basePackages = "com.wawj.core.mapper.master", sqlSessionTemplateRef = "masterSqlSessionTemplate") public class MasterDataSourceConfig {/ * create a data source * @ return * / @ Bean @ Primary @ ConfigurationProperties (prefix = "spring.datasource.master") public DataSource masterDataSource () {return DruidDataSourceBuilder.create () .build () } / * create a factory * @ param dataSource * @ return * @ throws Exception * / @ Bean @ Primary public SqlSessionFactory masterSqlSessionFactory (@ Qualifier ("masterDataSource") DataSource dataSource) throws Exception {SqlSessionFactoryBean bean = new SqlSessionFactoryBean (); bean.setDataSource (dataSource) / / specify the mapper.xml directory bean.setMapperLocations (new PathMatchingResourcePatternResolver () .getResources ("classpath:mapper/master/**/*.xml")); / / specify the entity class directory bean.setTypeAliasesPackage ("com.wawj.core.entity"); return bean.getObject () } / * create transaction * @ param dataSource * @ return * / @ Bean @ Primary public DataSourceTransactionManager masterTransactionManager (@ Qualifier ("masterDataSource") DataSource dataSource) {return new DataSourceTransactionManager (dataSource) } / * create template * @ param sqlSessionFactory * @ return * / @ Bean @ Primary public SqlSessionTemplate masterSqlSessionTemplate (@ Qualifier ("masterSqlSessionFactory") SqlSessionFactory sqlSessionFactory) {return new SqlSessionTemplate (sqlSessionFactory);}}
SlaveDataSourceConfig.java
Package com.core.dataSource;import com.alibaba.druid.spring.boot.autoconfigure.DruidDataSourceBuilder;import org.apache.ibatis.session.SqlSessionFactory;import org.mybatis.spring.SqlSessionFactoryBean;import org.mybatis.spring.SqlSessionTemplate;import org.mybatis.spring.annotation.MapperScan;import org.springframework.beans.factory.annotation.Qualifier;import org.springframework.boot.context.properties.ConfigurationProperties;import org.springframework.context.annotation.Bean;import org.springframework.context.annotation.Configuration;import org.springframework.context.annotation.Primary Import org.springframework.core.io.support.PathMatchingResourcePatternResolver;import org.springframework.jdbc.datasource.DataSourceTransactionManager;import javax.sql.DataSource / * mysql data configuration * / @ Configuration// configure the mapper file directory, scan @ MapperScan (basePackages = "com.wawj.core.mapper.slave", sqlSessionTemplateRef = "slaveSqlSessionTemplate") public class SlaveDataSourceConfig {/ * create a data source * @ return * / @ Bean @ ConfigurationProperties (prefix = "spring.datasource.slave") public DataSource slaveDataSource () {return DruidDataSourceBuilder.create () .build () } / * create a factory * @ param dataSource * @ return * @ throws Exception * / @ Bean public SqlSessionFactory slaveSqlSessionFactory (@ Qualifier ("slaveDataSource") DataSource dataSource) throws Exception {SqlSessionFactoryBean bean = new SqlSessionFactoryBean (); bean.setDataSource (dataSource) / / specify the mapper.xml directory bean.setMapperLocations (new PathMatchingResourcePatternResolver () .getResources ("classpath:mapper/slave/**/*.xml")); / / specify the entity class directory bean.setTypeAliasesPackage ("com.wawj.core.entity"); return bean.getObject () } / * create transaction * @ param dataSource * @ return * / @ Bean public DataSourceTransactionManager slaveTransactionManager (@ Qualifier ("slaveDataSource") DataSource dataSource) {return new DataSourceTransactionManager (dataSource) } / * create template * @ param sqlSessionFactory * @ return * / @ Bean public SqlSessionTemplate slaveSqlSessionTemplate (@ Qualifier ("slaveSqlSessionFactory") SqlSessionFactory sqlSessionFactory) {return new SqlSessionTemplate (sqlSessionFactory);}}
In this way, it is time to initialize the data source label in the druid console (http://localhost:8080/druid/login.html). The currently connected data source will not be displayed until the request has been made.
Dynamic configuration using dynamic-datasource (created when the project starts)
Pom.xml
Com.alibaba druid-spring-boot-starter 1.1.10 com.baomidou dynamic-datasource-spring-boot-starter 2.5.6 com.ojdbc ojdbc 10.2.0.1 system ${project.basedir} / src/main/lib/ojdbc14-10.2.0.1.0.jar mysql mysql-connector-java 5.1.38
Application.properties
# Global default values You can globally change the spring.datasource.dynamic.druid.initial-size=5spring.datasource.dynamic.druid.max-active=5spring.datasource.dynamic.druid.min-idle=5spring.datasource.dynamic.druid.pool-prepared-statements=true# configuration to execute multiple sql, for example: batch processing # error: sql injection violation, multi-statement not allowspring.datasource.dynamic.druid.wall.multi-statement-allow=true# configuration executes special sql, such as sql server's create temporary table (declare) statement # corresponding error: sql injection violation Class com.alibaba.druid.sql.ast.statement.SQLDeclareStatement not allowspring.datasource.dynamic.druid.wall.none-base-statement-allow=true#oracle Database spring.datasource.dynamic.datasource.master.driver-class-name=oracle.jdbc.OracleDriverspring.datasource.dynamic.datasource.master.druid.validation-query=SELECT 1 FROM DUALspring.datasource.dynamic.datasource.master.url=jdbc:oracle:thin:@localhost:1521:testspring.datasource.dynamic.datasource.master.username=oraclespring.datasource.dynamic.datasource.master.password=123456#mysql Database spring .datasource.dynamic.datasource.slave.driver-class-name=com.mysql.cj.jdbc.Driverspring.datasource.dynamic.datasource.slave.druid.validation-query=SELECT 1spring.datasource.dynamic.datasource.slave.url=jdbc:mysql://localhost:3306/test?characterEncoding=utf8spring.datasource.dynamic.datasource.slave.username=mysqlspring.datasource.dynamic.datasource.slave.password=123456# specifies master as the main data source spring.datasource.dynamic.primary=master# excludes the native Druid quick configuration class (DruidDataSourceAutoConfigure injects a DataSourceWrapper It will look for url,username,password and so on under the native spring.datasource. The configuration path of our dynamic data source is variable. ) spring.autoconfigure.exclude=com.alibaba.druid.spring.boot.autoconfigure.DruidDataSourceAutoConfigure# sets dynamic login name spring.datasource.druid.stat-view-servlet.login-username=admin# sets dynamic password spring.datasource.druid.stat-view-servlet.login-password=admin#mybatis mapper locationmybatis-plus.mapper-locations=classpath:mapper/**/*.xmlmybatis-plus.type-aliases-package=com.wawj.core.entity
This method uses annotations (@ DS ("data source name") to switch data sources
@ DS can be annotated on both methods and classes, and method annotations take precedence over class annotations.
Annotations are made on service implementations or mapper interface methods, but it is strongly not recommended to annotate both service and mapper. (there may be problems)
The annotation result does not have @ DS default data source @ DS ("dsName") dsName can be a group name or a specific library name
Add: excluding native DruidDataSourceAutoConfigure can also be excluded in the springboot startup class (some versions of springBoot may not be excluded. Just configure exclusion in application.properties)
@ SpringBootApplication (exclude= DruidDataSourceAutoConfigure.class) public class Application {public static void main (String [] args) {SpringApplication.run (Application.class, args);} or # application.propertiesspring.autoconfigure.exclude=com.alibaba.druid.spring.boot.autoconfigure.DruidDataSourceAutoConfigure after reading the above, do you have any further understanding of how to use mybatis to configure multiple data sources in springboot? If you want to know more knowledge or related content, please follow the industry information channel, thank you for your support.
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.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.