In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-01-17 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/01 Report--
This article is about how Springboot assembles two databases of the same type at the same time. The editor thinks it is very practical, so share it with you as a reference and follow the editor to have a look.
Assemble two databases of the same type simultaneously
1. Configuration file:
Spring: profiles: active: dev datasource: primary: jdbc-url: jdbc:sqlserver://localhost:1111;DatabaseName=DB1 driverClassName: com.microsoft.sqlserver.jdbc.SQLServerDriver type: com.alibaba.druid.pool.DruidDataSource username: root password: root secondary: jdbc-url: jdbc:sqlserver://localhost:1111;DatabaseName=DB2 driverClassName: com.microsoft.sqlserver.jdbc.SQLServerDriver type: com.alibaba.druid.pool.DruidDataSource username: root password: root
two。 Configuration class:
① main configuration class: DataSourceConfigPrimary
@ Configuration@MapperScan (basePackages = "com.message.dao.primary" SqlSessionFactoryRef = "primarySqlSessionFactory") public class DataSourceConfigPrimary {/ / put this object in the Spring container @ Bean (name = "primaryDataSource") / / indicates that this data source is the default data source @ Primary / / read the configuration parameter mapping in application.properties to an object / / prefix prefix @ ConfigurationProperties (prefix = "spring.datasource.primary") public DataSource getDateSourcePrimary () {return DataSourceBuilder.create () .build () } @ Bean (name = "primarySqlSessionFactory") / / indicates that this data source is the default data source @ Primary / / @ Qualifier means to find the object public SqlSessionFactory primarySqlSessionFactory (@ Qualifier ("primaryDataSource") DataSource datasource) throws Exception {SqlSessionFactoryBean bean = new SqlSessionFactoryBean (); bean.setDataSource (datasource) named test1DataSource in the Spring container. Bean.setMapperLocations (/ / sets the location of the xml of mybatis new PathMatchingResourcePatternResolver () .getResources ("classpath:mapper/primary/*.xml")); return bean.getObject () } @ Bean ("primarySqlSessionTemplate") / / indicates that this data source is the default data source @ Primary public SqlSessionTemplate primarySqlSessionTemplate (@ Qualifier ("primarySqlSessionFactory") SqlSessionFactory sessionFactory) {return new SqlSessionTemplate (sessionFactory);}}
② secondary configuration class: DataSourceConfigSecondary
@ Configuration@MapperScan (basePackages = "com.message.dao.secondary", sqlSessionFactoryRef = "secondarySqlSessionFactory") public class DataSourceConfigSecondary {@ Bean (name = "secondaryDataSource") @ ConfigurationProperties (prefix = "spring.datasource.secondary") public DataSource getDateSource2 () {return DataSourceBuilder.create (). Build ();} @ Bean (name = "secondarySqlSessionFactory") public SqlSessionFactory secondarySqlSessionFactory (@ Qualifier ("secondaryDataSource") DataSource datasource) throws Exception {SqlSessionFactoryBean bean = new SqlSessionFactoryBean () Bean.setDataSource (datasource); bean.setMapperLocations (new PathMatchingResourcePatternResolver (). GetResources ("classpath:mapper/secondary/*.xml")); return bean.getObject ();} @ Bean ("secondarySqlSessionTemplate") public SqlSessionTemplate secondarySqlSessionTemplate (@ Qualifier ("secondarySqlSessionFactory") SqlSessionFactory sessionFactory) {return new SqlSessionTemplate (sessionFactory);}}
3. Scan XML
4. Startup class:
@ SpringBootApplication (scanBasePackages = {"com.lalal.*"}) public class MessageApplication extends SpringBootServletInitializer {public static void main (String [] args) {SpringApplication.run (MessageApplication.class, args);} @ Bean public RestTemplate restTemplate () {return new RestTemplate ();}} configure to connect two or more databases
Background:
In the project, you need to query data from two different databases, which were previously implemented by springboot configuration to connect to one data source and the other to connect using jdbc code.
To improve, now use SpringBoot configuration to connect two data sources
Achieve results:
A SpringBoot project that connects two databases at the same time: for example, one is a pgsql database and the other is an oracle database
(any database is the same. If you connect two databases with the same oracle or two different databases, you only need to change the corresponding driver-class-name, jdbc-url, etc.)
Note: what database to connect to, the package of the corresponding database should be introduced.
Implementation steps:
1. Modify application.yml to add a database connection configuration
(I have the yml format here, and the suffix properties format is the same
Server: port: 7101spring: jpa: show-sql: true datasource: test1: driver-class-name: org.postgresql.Driver jdbc-url: jdbc:postgresql://127.0.0.1:5432/test # Test Database username: root password: root test2: driver-class-name: oracle.jdbc.driver.OracleDriver jdbc-url: jdbc:oracle:thin:@127.0.0.1:8888 : orcl # Test Database username: root password: root
Pay special attention to:
(1) use test1 and test2 to distinguish between two database connections
(2) change url to: jdbc-url
2. Use code for data source injection and scan the dao layer path (previously, the path of mybatis scanning dao was configured in the yml file)
Create a new config package containing configuration files for database 1 and database 2
(1) the first database is used as the master database, and the project starts to connect to this database by default
DataSource1Config.java
Package com.test.config; 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.boot.jdbc.DataSourceBuilder;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; @ Configuration@MapperScan (basePackages = "com.test.dao.test1", sqlSessionTemplateRef = "test1SqlSessionTemplate") public class DataSource1Config {@ Bean (name = "test1DataSource") @ ConfigurationProperties (prefix = "spring.datasource.test1") @ Primary public DataSource testDataSource () {return DataSourceBuilder.create () .build } @ Bean (name = "test1SqlSessionFactory") @ Primary public SqlSessionFactory testSqlSessionFactory (@ Qualifier ("test1DataSource") DataSource dataSource) throws Exception {SqlSessionFactoryBean bean = new SqlSessionFactoryBean (); bean.setDataSource (dataSource); bean.setMapperLocations (new PathMatchingResourcePatternResolver (). GetResources ("classpath:test1/*.xml")); return bean.getObject () @ Bean (name = "test1TransactionManager") @ Primary public DataSourceTransactionManager testTransactionManager (@ Qualifier ("test1DataSource") DataSource dataSource) {return new DataSourceTransactionManager (dataSource);} @ Bean (name = "test1SqlSessionTemplate") @ Primary public SqlSessionTemplate testSqlSessionTemplate (@ Qualifier ("test1SqlSessionFactory") SqlSessionFactory sqlSessionFactory) throws Exception {return new SqlSessionTemplate (sqlSessionFactory);}}
Pay special attention to:
(1) all master databases have @ Primary annotations, but none from slave databases.
(2) the second database acts as a slave database.
DataSource2Config.java
Package com.test.config; 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.boot.jdbc.DataSourceBuilder;import org.springframework.context.annotation.Bean;import org.springframework.context.annotation.Configuration;import org.springframework.core.io.support.PathMatchingResourcePatternResolver;import org.springframework.jdbc.datasource.DataSourceTransactionManager Import javax.sql.DataSource; @ Configuration@MapperScan (basePackages = "com.test.dao.test2", sqlSessionTemplateRef = "test2SqlSessionTemplate") public class DataSource2Config {@ Bean (name = "test2DataSource") @ ConfigurationProperties (prefix = "spring.datasource.test2") public DataSource testDataSource () {return DataSourceBuilder.create (). Build ();} @ Bean (name = "test2SqlSessionFactory") public SqlSessionFactory testSqlSessionFactory (@ Qualifier ("test2DataSource") DataSource dataSource) throws Exception {SqlSessionFactoryBean bean = new SqlSessionFactoryBean () Bean.setDataSource (dataSource); bean.setMapperLocations (new PathMatchingResourcePatternResolver (). GetResources ("classpath:test2/*.xml")); return bean.getObject ();} @ Bean (name = "test2TransactionManager") public DataSourceTransactionManager testTransactionManager (@ Qualifier ("test2DataSource") DataSource dataSource) {return new DataSourceTransactionManager (dataSource) } @ Bean (name = "test2SqlSessionTemplate") public SqlSessionTemplate testSqlSessionTemplate (@ Qualifier ("test2SqlSessionFactory") SqlSessionFactory sqlSessionFactory) throws Exception {return new SqlSessionTemplate (sqlSessionFactory);}}
3. Under the dao folder, create two new packages, test1 and test2, and put the dao layer files of two different databases.
(1) TestDao1.java
@ Componentpublic interface TestDao1 {List selectDailyActivity ();}
(2) TestDao2.java
@ Componentpublic interface TestDao2 {List selectDailyActivity ();}
4. Create two folders, test1 and test2, under resource, and place them in the xml files of the corresponding dao layer.
(the xml file of the dao of my original project is in the resource directory, and you can do it in your own project directory.)
Note that the names of dao's java file and dao's xml file should be the same.
(1) TestDao1.xml
SELECT * FROM daily_activity_data_middle
(2) TestDao2.xml
SELECT * FROM movieshowtest
5. Test
In the controller file, inject the dao of the two databases to query the data respectively
@ RestControllerpublic class TestController extends BaseController {@ Autowired private PropertiesUtils propertiesUtils; @ Autowired private TestDao1 testDao1; @ Autowired private TestDao2 testDao2; @ RequestMapping (value = {"/ test/test1"}, method = RequestMethod.POST) public Result DataStatistics (@ RequestBody JSONObject body) throws Exception {Result result = new Result (ICommon.SUCCESS, propertiesUtils.get (ICommon.SUCCESS)); JSONObject object = new JSONObject (); object.put ("data", testDao1.selectDailyActivity ()) Result.setResult (object); return result;} @ RequestMapping (value = {"/ test/test2"}, method = RequestMethod.POST) public Result DataStatisticsaa (@ RequestBody JSONObject body) throws Exception {Result result = new Result (ICommon.SUCCESS, propertiesUtils.get (ICommon.SUCCESS)); JSONObject object = new JSONObject (); object.put ("data", testDao2.selectDailyActivity ()); result.setResult (object); return result Thank you for your reading! This is the end of the article on "how Springboot assembles two databases of the same type at the same time". I hope the above content can be of some help to you, so that you can learn more knowledge. if you think the article is good, you can share it for more people to see!
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.