In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-01-18 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/02 Report--
This article mainly introduces "how to realize dual data sources in SpringBoot+Jpa project configuration". In daily operation, I believe many people have doubts about how to realize dual data sources in SpringBoot+Jpa project configuration. The editor consulted all kinds of materials and sorted out simple and easy-to-use operation methods. I hope it will be helpful to answer the doubts of "how to realize dual data sources in SpringBoot+Jpa project configuration". Next, please follow the editor to study!
Configure the yml file
Server: port: 8080spring: profiles: active: dev jackson: time-zone: GMT+8 # here is our database configuration datasource: data1: # here is the database-driverClassName: com.mysql.cj.jdbc.Driver url: jdbc:mysql://192.168.0.77:3306/test1?characterEncoding=UTF-8&serverTimezone=Asia/Shanghai&autoReconnect=true&failOverReadOnly=false&rewriteBatchedStatements=true username: root password: 123 Type: com.alibaba.druid.pool.DruidDataSource data2: # this is database two: driverClassName: com.mysql.cj.jdbc.Driver url: jdbc:mysql://192.168.0.88:3306/test2?characterEncoding=UTF-8&serverTimezone=Asia/Shanghai&autoReconnect=true&failOverReadOnly=false&rewriteBatchedStatements=true username: root password: 123type: com.alibaba.druid.pool.DruidDataSource
Of course, there must be no end here. Some parameters need to be configured, otherwise the startup will report an error.
Create a data source configuration class
When we create a class for a data source, we name it DataSourceConfig (the name is customized), and create a package under the project for easy management.
Package com.eman.cdn.common.dataSource;import org.springframework.beans.factory.annotation.Qualifier;import org.springframework.boot.autoconfigure.ImportAutoConfiguration;import org.springframework.boot.autoconfigure.jdbc.DataSourceProperties;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 javax.sql.DataSource / * * @ author https://blog.csdn.net/weixin_42782429?spm=1000.2115.3001.5343 * @ date 11:35 on 2021-12-21 *
* description data source configuration * / @ Configurationpublic class DataSourceConfig {# this is the location we configured in the yml file private final static String DB_TEST1 = "spring.datasource.test1"; private final static String DB_TEST2= "spring.datasource.test1" # the Bean name is customized as long as it is not a duplicate Bean name @ Bean (name = "test1Properties") @ Qualifier ("test1Properties") @ Primary @ ConfigurationProperties (DB_TEST1) public DataSourceProperties test1Properties () {return new DataSourceProperties () } @ Bean (name = "test1DataSource") @ Qualifier ("test1DataSource") @ Primary @ ConfigurationProperties (prefix = DB_TEST1) public DataSource test1DataSource () {return test1Properties (). InitializeDataSourceBuilder (). Build ();} @ Bean (name = "test2Properties") @ Qualifier ("test2Properties") @ ConfigurationProperties (DB_TEST2) public DataSourceProperties test2Properties () {return new DataSourceProperties () } @ Bean (name = "test2DataSource") @ Qualifier ("test2DataSource") @ ConfigurationProperties (prefix = DB_ANALYSIS) public DataSource test2DataSource () {return test2Properties () .initializeDataSourceBuilder () .build ();}} create configuration classes for each database
Since you need to use Mybaitis-plus, you have to import Mybaitis-Plus 's dependencies first.
Com.baomidou mybatis-plus-boot-starter 3.1.0 package com.eman.xx.xxx.xx;import com.baomidou.mybatisplus.extension.spring.MybatisSqlSessionFactoryBean;import org.apache.ibatis.session.SqlSessionFactory;import org.mybatis.spring.SqlSessionTemplate;import org.mybatis.spring.annotation.MapperScan;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.beans.factory.annotation.Qualifier;import org.springframework.boot.autoconfigure.orm.jpa.HibernateProperties Import org.springframework.boot.autoconfigure.orm.jpa.HibernateSettings;import org.springframework.boot.autoconfigure.orm.jpa.JpaProperties;import org.springframework.boot.orm.jpa.EntityManagerFactoryBuilder;import org.springframework.context.annotation.Bean;import org.springframework.context.annotation.Configuration;import org.springframework.core.io.support.PathMatchingResourcePatternResolver;import org.springframework.data.jpa.repository.config.EnableJpaRepositories;import org.springframework.orm.jpa.JpaTransactionManager;import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean;import org.springframework.transaction.PlatformTransactionManager Import org.springframework.transaction.annotation.EnableTransactionManagement;import javax.sql.DataSource;import java.util.Objects;/** * @ author tongJie * @ date 11:59 on 2021-12-21 *
* description log processor database configuration * / @ Configuration@EnableTransactionManagement@EnableJpaRepositories (/ / configure connection factory entityManagerFactoryRef = "tes1Factory", / / configure transaction manager transactionManagerRef = "tes1Transaction" / / set the repository location of Jpa basePackages = {"com.xx.xx.xx.**.repository"}) / / set the scanned mapper@MapperScan (basePackages = "xx.xx.xx.test1.**.mapper", sqlSessionTemplateRef = "tes1SqlSessionTemplate") public class AnalysisDataBaseConfig {@ Autowired @ Qualifier ("tes1DataSource") private DataSource analysisDataSource @ Autowired private JpaProperties jpaProperties; @ Autowired private HibernateProperties properties / / the following is the jpa configuration / * connection factory * @ param builder creation tool * @ return result * / @ Bean (name = "tes1Factory") public LocalContainerEntityManagerFactoryBean tes1Factory (EntityManagerFactoryBuilder builder) {return builder / / sets the data source .dataSource (analysisDataSource) / / sets the location of the entity class. Scanning all classes with @ Entity annotations. Xx.xx.xx.tes1.**.entity ("xx.xx.xx.tes1.**.entity") / / Spring injects EntityManagerFactory into Repository. With EntityManagerFactory, / / Repository can use it to create EntityManager, and then EntityManager can perform operations on the database. PersistenceUnit ("tes1") / / in order to load the related configuration of hibernate under jpa in yml. Properties (properties.determineHibernateProperties (jpaProperties.getProperties (), new HibernateSettings () .build () } / * configure the transaction manager * * @ param builder creation tool * @ return result * / @ Bean (name = "tes1Transaction") PlatformTransactionManager tes1Transaction (EntityManagerFactoryBuilder builder) {return new JpaTransactionManager (Objects.requireNonNull (analysisFactory (builder). GetObject () } / / the following is the configuration of mybatis / * configure sqlSessionFactory * @ return result * @ throws Exception exception * / @ Bean ("tes1SqlSessionFactory") public SqlSessionFactory tes1SqlSessionFactory () throws Exception {MybatisSqlSessionFactoryBean sqlSessionFactory = new MybatisSqlSessionFactoryBean (); sqlSessionFactory.setDataSource (analysisDataSource) SqlSessionFactory.setMapperLocations (new / / fill in the path where your mybaits's xml file is stored PathMatchingResourcePatternResolver (). GetResources ("classpath:mybatis/mapper/*.xml"); return sqlSessionFactory.getObject ();} / * configure sqlSessionTemplate * @ return result * / @ Bean (name = "tes1SqlSessionTemplate") public SqlSessionTemplate tes1SqlSessionTemplate () throws Exception {return new SqlSessionTemplate (tes1SqlSessionFactory ());}}
Attention! The package must be placed in the right location, otherwise an error will be reported if you do not identify it!
At this point, the study on "how to configure dual data sources in the SpringBoot+Jpa project" is over. I hope to be able to solve your doubts. The collocation of theory and practice can better help you learn, go and try it! If you want to continue to learn more related knowledge, please continue to follow the website, the editor will continue to work hard to bring you more practical articles!
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.