时间:2023-01-11 10:46:31 | 栏目:JAVA代码 | 点击:次
今天为大家带来一些非常有用的实战技巧,比如在我们需要对两个数据库进行操作的时候而哦我们通常用的只是单数据库查询,这就触及到知识盲点了,那么废话不多说上代码!
server: port: 8080 spring: 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; /** * @author https://blog.csdn.net/weixin_42782429?spm=1000.2115.3001.5343 * @date 2021/12/21 11:35 * <p> * description 数据源配置 */ @Configuration public 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; /** * @author tongJie * @date 2021/12/21 11:59 * <p> * description 日志处理端数据库配置 */ @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的配置 /** * 连接工厂 * @param builder 创建工具 * @return 结果 */ @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(); } /** * 配置事物管理器 * * @param builder 创建工具 * @return 结果 */ @Bean(name = "tes1Transaction") PlatformTransactionManager tes1Transaction(EntityManagerFactoryBuilder builder) { return new JpaTransactionManager(Objects.requireNonNull(analysisFactory(builder).getObject())); } // 以下是mybatis的配置 /** * 配置sqlSessionFactory * @return 结果 * @throws Exception 异常 */ @Bean("tes1SqlSessionFactory") public SqlSessionFactory tes1SqlSessionFactory() throws Exception { MybatisSqlSessionFactoryBean sqlSessionFactory = new MybatisSqlSessionFactoryBean(); sqlSessionFactory.setDataSource(analysisDataSource); sqlSessionFactory.setMapperLocations(new //这里填写你mybaits的xml文件存放的路径 PathMatchingResourcePatternResolver().getResources("classpath:mybatis/mapper/*.xml")); return sqlSessionFactory.getObject(); } /** * 配置sqlSessionTemplate * @return 结果 */ @Bean(name = "tes1SqlSessionTemplate") public SqlSessionTemplate tes1SqlSessionTemplate() throws Exception { return new SqlSessionTemplate(tes1SqlSessionFactory()); } }
以此类推之后每增加一个数据库源就循环上面的方法
注意!!!!包一定要放对你配置的位置,否则不识别就会报错!!!!!!