这篇文章主要介绍“SpringBoot+Jpa项目配置双数据源怎么实现”,在日常操作中,相信很多人在SpringBoot+Jpa项目配置双数据源怎么实现问题上存在疑惑,小编查阅了各式资料,整理出简单好用的操作方法,希望对大家解答”SpringBoot+Jpa项目配置双数据源怎么实现”的疑惑有所帮助!接下来,请跟着小编一起来学习吧!
配置yml文件
server: port: 8080spring: profiles: active: dev jackson: time-zone: GMT+8 # 这里是我们的数据库配置地方 datasource: data1: #这里是数据库一 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: #这里是数据库二 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: 123 type: com.alibaba.druid.pool.DruidDataSource
当然到这里肯定是没有结束的,需要配置一些参数,否则启动会报错
创建数据源配置类
我们创建一个数据源的类,我们就给他取名为DataSourceConfig(这个名字自定义),在项目下创建一个包,方便管理
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;@Configurationpublic class DataSourceConfig { # 这里是我们在yml文件配置的位置 private final static String DB_TEST1 = "spring.datasource.test1"; private final static String DB_TEST2= "spring.datasource.test1"; # 这个Bean名字子自定义只要不是重复的Bean名字就行了 @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(); }}
为每个数据库创建配置类
由于需要用到Mybaitis-plus所以你得先导入Mybaitis-Plus的依赖
<!--mybatis-plus--> <dependency> <groupId>com.baomidou</groupId> <artifactId>mybatis-plus-boot-starter</artifactId> <version>3.1.0</version> </dependency>
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;@Configuration@EnableTransactionManagement@EnableJpaRepositories( // 配置连接工厂 entityManagerFactoryRef = "tes1Factory", // 配置事物管理器 transactionManagerRef = "tes1Transaction", // 设置Jpa 的 repository所在位置 basePackages = {"com.xx.xx.xx.**.repository"})// 设置扫描的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; // 以下是jpa的配置 @Bean(name = "tes1Factory") public LocalContainerEntityManagerFactoryBean tes1Factory(EntityManagerFactoryBuilder builder) { return builder // 设置数据源 .dataSource(analysisDataSource) //设置实体类所在位置.扫描所有带有 @Entity 注解的类 .packages("xx.xx.xx.tes1.**.entity") // Spring会将EntityManagerFactory注入到Repository之中.有了 EntityManagerFactory之后, // Repository就能用它来创建 EntityManager 了,然后 EntityManager 就可以针对数据库执行操作 .persistenceUnit("tes1") // 为了加载yml中jpa下hibernate的相关配置 .properties(properties.determineHibernateProperties(jpaProperties.getProperties(), new HibernateSettings())) .build(); } @Bean(name = "tes1Transaction") PlatformTransactionManager tes1Transaction(EntityManagerFactoryBuilder builder) { return new JpaTransactionManager(Objects.requireNonNull(analysisFactory(builder).getObject())); } // 以下是mybatis的配置 @Bean("tes1SqlSessionFactory") public SqlSessionFactory tes1SqlSessionFactory() throws Exception { MybatisSqlSessionFactoryBean sqlSessionFactory = new MybatisSqlSessionFactoryBean(); sqlSessionFactory.setDataSource(analysisDataSource); sqlSessionFactory.setMapperLocations(new //这里填写你mybaits的xml文件存放的路径 PathMatchingResourcePatternResolver().getResources("classpath:mybatis/mapper @Bean(name = "tes1SqlSessionTemplate") public SqlSessionTemplate tes1SqlSessionTemplate() throws Exception { return new SqlSessionTemplate(tes1SqlSessionFactory()); }}
以此类推之后每增加一个数据库源就循环上面的方法
注意!!!!包一定要放对你配置的位置,否则不识别就会报错!!!!!!
到此,关于“SpringBoot+Jpa项目配置双数据源怎么实现”的学习就结束了,希望能够解决大家的疑惑。理论与实践的搭配能更好的帮助大家学习,快去试试吧!若想继续学习更多相关知识,请继续关注编程网网站,小编会继续努力为大家带来更多实用的文章!