In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-02-22 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/02 Report--
This article mainly shows you "how to build multiple data sources in SpringBoot". The content is simple and clear. I hope it can help you solve your doubts. Let the editor lead you to study and learn this article "how to build multiple data sources in SpringBoot".
First, let's set up two databases (which may not be on the same computer):
Multiple_order:
DROP DATABASE IF EXISTS `multiple_ order`; CREATE DATABASE `multiple_ order`; USE `order`; CREATE TABLE `order` (`user_ id`BIGINT UNSIGNED PRIMARY KEY AUTO_INCREMENT COMMENT 'order id', `user_ id`order` user id', `cost`DECIMAL (13,2) COMMENT' order fee') COMMENT 'order form'
Multiple_user:
DROP DATABASE IF EXISTS `multiple_ user`; CREATE DATABASE `multiple_ user`; USE `user`; CREATE TABLE `user` (`user_ id`user` user id', `username` VARCHAR (50) NOT NULL COMMENT 'username', `age`TINYINT UNSIGNED COMMENT 'age) COMMENT' user Table'
Then create a maven project where the pom.xml file:
4.0.0 org.springframework.boot spring-boot-starter-parent 2.3.9.RELEASE love.xiaohh.datasource multiple-datasources 1.0-SNAPSHOT 8 8 org.springframework.boot spring-boot-starter-web org.springframework. Boot spring-boot-starter-actuator org.mybatis.spring.boot mybatis-spring-boot-starter 2.2.0 mysql mysql-connector-java com.alibaba fastjson 1. 2.78 org.springframework.boot spring-boot-maven-plugin
There are two data sources that need to be configured in application.yml:
Spring: datasource: # user module database configuration user: driver-class-name: com.mysql.cj.jdbc.Driver jdbc-url: jdbc:mysql://127.0.0.1:3306/multiple_user?useUnicode=true&characterEncoding=utf8&zeroDateTimeBehavior=convertToNull&useSSL=true&serverTimezone=GMT%2B8 username: root password: xiaohh # order module database configuration order: driver-class-name: com.mysql.cj.jdbc .driver jdbc-url: jdbc:mysql://127.0.0.1:3306/multiple_order?useUnicode=true&characterEncoding=utf8&zeroDateTimeBehavior=convertToNull&useSSL=true&serverTimezone=GMT%2B8 username: root password: xiaohhmybatis: # Mapper directory mapper-locations: classpath:mapper/**/*Mapper.xml
Then we define a configuration class DataSourseConfig to configure multiple data sources. The first step is to declare the data source and define two data sources according to the configuration in application.yml. Note that the DataSource is javax.sql.DataSource:
/ * * configure the user's data source * * @ return user's data source object * / @ Primary / / requires a default configured data source @ Bean ("user") @ ConfigurationProperties (prefix = "spring.datasource.user") / / configure the prefix public DataSource user () {return DataSourceBuilder.create (). Build () of the data source in yml. } / * * configure data source of order * * @ data source object of return order * / @ Bean ("order") @ ConfigurationProperties (prefix = "spring.datasource.order") / / configure the prefix public DataSource order () {return DataSourceBuilder.create (). Build () of the data source in yml;}
Then create the SqlSessionFactory:
/ * * registered user's SqlSession factory * * @ param user data source * @ return SqlSession factory * @ throws Exception may throw an exception * / @ Primary / / configure a default bean@Bean ("userSqlSessionFactory") public SqlSessionFactory userSqlSessionFactory (@ Qualifier ("user") DataSource user) throws Exception {/ / create bean SqlSessionFactoryBean factory = new SqlSessionFactoryBean (); / / set the data source factory.setDataSource (user) / / sets the scanning factory.setMapperLocations of mapper files (new PathMatchingResourcePatternResolver () .getResources ("classpath:mapper/user/*.xml")); return factory.getObject () } / * SqlSession factory that registers the order * * @ param order data source * @ return SqlSession factory * @ throws Exception may throw an exception * / @ Bean ("orderSqlSessionFactory") public SqlSessionFactory orderSqlSessionFactory (@ Qualifier ("order") DataSource order) throws Exception {/ / create bean SqlSessionFactoryBean factory = new SqlSessionFactoryBean (); / / set data source factory.setDataSource (order) / / set the scan factory.setMapperLocations for mapper files (new PathMatchingResourcePatternResolver () .getResources ("classpath:mapper/order/*.xml")); return factory.getObject ();}
Finally, declare two SqlSessionTemplate:
/ * user's SqlSessionTemplate * @ param userSqlSessionFactory user's SqlSession factory * @ return user's SqlSessionTemplate * / @ Primary / / set this type of default bean@Bean ("userSqlSessionTemplate") public SqlSessionTemplate userSqlSessionTemplate (@ Qualifier ("userSqlSessionFactory") SqlSessionFactory userSqlSessionFactory) {return new SqlSessionTemplate (userSqlSessionFactory) } / * * SqlSessionTemplate * * @ param orderSqlSessionFactory order SqlSession factory * @ return user's SqlSessionTemplate * / @ Bean ("orderSqlSessionTemplate") public SqlSessionTemplate orderSqlSessionTemplate (@ Qualifier ("orderSqlSessionFactory") SqlSessionFactory orderSqlSessionFactory) {return new SqlSessionTemplate (orderSqlSessionFactory);}
Finally, don't forget to add a note to the configuration class to declare which Mapper files use which annotations:
@ Configuration@MapperScans ({/ / basePackages is the package path of mapper, and sqlSessionTemplateRef is the SqlSessionTemplate @ MapperScan that we created (basePackages = "love.xiaohh.datasource.mapper.user", sqlSessionTemplateRef = "userSqlSessionTemplate"), @ MapperScan (basePackages = "love.xiaohh.datasource.mapper.order", sqlSessionTemplateRef = "orderSqlSessionTemplate")})
The complete code for the DataSourceConfig class:
Package love.xiaohh.datasource.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.mybatis.spring.annotation.MapperScans;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 javax.sql.DataSource;/** *
* configuration classes of multiple data sources *
* * @ author XiaoHH * @ version 1.0 * @ date 2021-12-03 Friday 11:15:06 * @ file DataSourceConfig.java * / @ Configuration@MapperScans ({/ / basePackages is the packet path of mapper SqlSessionTemplateRef specifies that we create SqlSessionTemplate @ MapperScan (basePackages = "love.xiaohh.datasource.mapper.user", sqlSessionTemplateRef = "userSqlSessionTemplate"), @ MapperScan (basePackages = "love.xiaohh.datasource.mapper.order") SqlSessionTemplateRef = "orderSqlSessionTemplate")}) public class DataSourceConfig {/ * * configure the user's data source * * @ return user's data source object * / @ Primary / / requires a default configured data source @ Bean ("user") @ ConfigurationProperties (prefix = "spring.datasource.user") / / configure the prefix public DataSource user () of the data source in yml {return DataSourceBuilder.create () .build () } / * configure data source of order * * @ data source object of return order * / @ Bean ("order") @ ConfigurationProperties (prefix = "spring.datasource.order") / / configure the prefix public DataSource order () {return DataSourceBuilder.create (). Build () of the data source in yml } / * registered user's SqlSession factory * * @ param user data source * @ return SqlSession factory * @ throws Exception may throw an exception * / @ Primary / / configure a default bean @ Bean ("userSqlSessionFactory") public SqlSessionFactory userSqlSessionFactory (@ Qualifier ("user") DataSource user) throws Exception {/ / of this type Create bean SqlSessionFactoryBean factory = new SqlSessionFactoryBean () / / set the data source factory.setDataSource (user); / / set the scanning factory.setMapperLocations of the mapper file (new PathMatchingResourcePatternResolver (). GetResources ("classpath:mapper/user/*.xml")); return factory.getObject () } / * SqlSession factory that registers the order * * @ param order data source * @ return SqlSession factory * @ throws Exception may throw an exception * / @ Bean ("orderSqlSessionFactory") public SqlSessionFactory orderSqlSessionFactory (@ Qualifier ("order") DataSource order) throws Exception {/ / create bean SqlSessionFactoryBean factory = new SqlSessionFactoryBean () / / set the data source factory.setDataSource (order); / / set the scanning factory.setMapperLocations of the mapper file (new PathMatchingResourcePatternResolver (). GetResources ("classpath:mapper/order/*.xml")); return factory.getObject () } / * * user's SqlSessionTemplate * * @ param userSqlSessionFactory user's SqlSession factory * @ return user's SqlSessionTemplate * / @ Primary / / set this type of default bean @ Bean ("userSqlSessionTemplate") public SqlSessionTemplate userSqlSessionTemplate (@ Qualifier ("userSqlSessionFactory") SqlSessionFactory userSqlSessionFactory) {return new SqlSessionTemplate (userSqlSessionFactory) SqlSessionTemplate * * @ SqlSession factory of param orderSqlSessionFactory order * @ return user's SqlSessionTemplate * / @ Bean ("orderSqlSessionTemplate") public SqlSessionTemplate orderSqlSessionTemplate (@ Qualifier ("orderSqlSessionFactory") SqlSessionFactory orderSqlSessionFactory) {return new SqlSessionTemplate (orderSqlSessionFactory);}}
Then create two Mapper interfaces according to the package defined above in the annotation
OrderMapper:
Package love.xiaohh.datasource.mapper.order;import love.xiaohh.datasource.entities.order.Order;import org.apache.ibatis.annotations.Mapper;import java.util.List;/** *
* Database access interface for order *
* * @ author tanghai * @ version 1.0 * @ date 2021-12-03 Friday 14:08:19 * @ file OrderMapper.java * / @ Mapperpublic interface OrderMapper {/ * add an order entity * * @ param order order entity * @ return affected lines * / int insertOrder (Order order) / * query a list of orders * * @ param order query parameters * @ return list of eligible orders * / List selectOrder (Order order);}
UserMapper:
Package love.xiaohh.datasource.mapper.user;import love.xiaohh.datasource.entities.user.User;import org.apache.ibatis.annotations.Mapper;import java.util.List;/** *
* user's database access interface *
* * @ author tanghai * @ version 1.0 * @ date 2021-12-03 Friday 14:11:55 * @ file UserMapper.java * / @ Mapperpublic interface UserMapper {/ * add a user * * @ param user user object * @ return affected rows * / int insertUser (User user) / * query user list * * @ param user query parameters * @ return list of eligible users * / List selectUser (User user);}
After that, I will submit the code to gitee, so the Mapper.xml, Controller, Service code is omitted here, and then we add a few pieces of user data:
Check it out:
At the same time order database:
Query:
Then check in the database to see if it is sent to a different database:
To be sure, it is indeed stored in two databases.
The above is all the content of the article "how to build multiple data sources in SpringBoot". Thank you for reading! I believe we all have a certain understanding, hope to share the content to help you, if you want to learn more knowledge, 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.
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.