Spring boot 多数据源配置(Mybatics+JPA)

Spring boot 配置数据源

spring:
  mvc:
    favicon:
      enabled: false
  datasource:
    primary:
      username: root
      password: root
      jdbc-url: mysql://127.0.0.1:3306/a?useUnicode=true
      driver-class-name: com.mysql.jdbc.Driver
      dbcp2:
        initial-size: 5
        min-idle: 5
        max-idle: 100
        max-wait-millis: 10000
        validation-query: SELECT 1

    secondary:
      username: root
      password: root
      jdbc-url: mysql://127.0.0.1:3306/b?useUnicode=true
      driver-class-name: com.mysql.jdbc.Driver
      dbcp2:
        initial-size: 5
        min-idle: 5
        max-idle: 100
        max-wait-millis: 10000
        validation-query: SELECT 1

其中,***primary***和***secondary***是数据源配置,可以配置多个。

数据源配置项

@Configuration
public class DataSourceConfig {

	@Primary
	@Bean(name="primaryDataSource")
	@Qualifier("primaryDataSource")
	@ConfigurationProperties(prefix="spring.datasource.primary")// 这里和application.yml中数据源的路径一直
	public DataSource primaryDataSource() {
		return DataSourceBuilder.create().build();
	}

	@Bean(name="secondaryDataSource")
	@Qualifier("secondaryDataSource")
	@ConfigurationProperties(prefix="spring.datasource.secondary")// 这里和application.yml中数据源的路径一直
	public DataSource secondaryDataSource() {
		return DataSourceBuilder.create().build();
	}
}

@Primary

表示:首选的数据源

@Primary

表示:有多个相同类实例的时候,用于区域不同的实例

数据源配置项内容——primary

@Configuration
@EnableTransactionManagement
@EnableJpaRepositories(
		entityManagerFactoryRef="entityManagerFactoryPrimary", 
		transactionManagerRef="transactionManagerPrimary")
@EntityScan(basePackages= "com.lance.server.*.model")

@MapperScan(basePackages = "com.lance.server.*.dao", sqlSessionTemplateRef = "primarySqlSessionTemplate")
public class PrimaryConfig {
	
	@Autowired 
	@Qualifier("primaryDataSource") // 使用了DataSourceConfig中的primaryDataSource
	private DataSource primaryDataSource;


	/** JPA ***/

    @Primary
    @Bean(name="entityManagerFactoryPrimary")
	public LocalContainerEntityManagerFactoryBean entityManagerFactoryPrimary(EntityManagerFactoryBuilder build) {
		return build.dataSource(primaryDataSource).
				packages("com.lance.server.*.model").
				persistenceUnit("primaryPersistenceUnit").
				build();
	}

    @Primary
    @Bean(name = "entityManagerPrimary")
	public EntityManager entityManager(EntityManagerFactoryBuilder builder) {
		return entityManagerFactoryPrimary(builder).getObject().createEntityManager();
	}
    
    @Primary
    @Bean(name = "transactionManagerPrimary")
    public PlatformTransactionManager transactionManagerPrimary(EntityManagerFactoryBuilder builder) {
        return new JpaTransactionManager(entityManagerFactoryPrimary(builder).getObject());
    }


    /**mybatits 多数据源配置***/

    /***
     * Mybatics 连接池
     * @author Lance [email protected]
     * @date 2019-09-21 11:58
     * @param
     * @return org.apache.ibatis.session.SqlSessionFactory
     *
     * */
	@Primary
	@Bean(name = "primarySqlSessionFactory")
    public SqlSessionFactory primarySqlSessionFactory(@Qualifier("primaryDataSource") DataSource dataSource) throws Exception {
		SqlSessionFactoryBean sqlSessionFactoryBean = new SqlSessionFactoryBean();
		sqlSessionFactoryBean.setDataSource(dataSource);
		sqlSessionFactoryBean.setMapperLocations(
				new PathMatchingResourcePatternResolver().getResources("classpath:mapper/primary/**/*.xml"));
		return sqlSessionFactoryBean.getObject();
	}

	/***
	 * Mybatics 事务控制
	 * @author Lance [email protected]
	 * @date 2019-09-21 11:58
	 * @param
	 * @return org.springframework.jdbc.datasource.DataSourceTransactionManager
	 *
	 * */
	@Primary
	@Bean(name = "primaryDataSourceTransactionManager")
	public DataSourceTransactionManager primaryDataSourceTransactionManager(@Qualifier("primaryDataSource") DataSource dataSource) {
		return new DataSourceTransactionManager(dataSource);
	}

	/***
	 * mybatics 模板
	 * @author Lance [email protected]
	 * @date 2019-09-21 11:57
	 * @param sqlSessionFactory
	 * @return org.mybatis.spring.SqlSessionTemplate
	 * 
	 * */
	@Primary
	@Bean(name = "primarySqlSessionTemplate")
	public SqlSessionTemplate primarySqlSessionTemplate(@Qualifier("primarySqlSessionFactory") SqlSessionFactory sqlSessionFactory) {
		return new SqlSessionTemplate(sqlSessionFactory);
	}
}

@EnableJpaRepositories

表示:JPA数据库操作注解,指定实例管理工厂和实例事务

@MapperScan

表示:Mybatics数据库操作映射文件,主要是映射路径和指定的SQL操作Session工厂,如果不指定,默认都会选择`@Primary`的首选SQL Session连接池

数据源配置项内容——Secondary

@Configuration
@EnableTransactionManagement
@EnableJpaRepositories(entityManagerFactoryRef = "entityManagerFactorySecondary",
        transactionManagerRef = "transactionManagerSecondary")
@EntityScan(basePackages = "com.lance.server.secondary.**.model")

@MapperScan(basePackages = "com.lance.server.secondary.**.dao", sqlSessionTemplateRef = "secondarySqlSessionTemplate")
public class SecondaryConfig {

    @Autowired
    @Qualifier("secondaryDataSource")
    private DataSource secondaryDataSource;


    /** JPA ***/

    @Bean(name = "entityManagerFactorySecondary")
    public LocalContainerEntityManagerFactoryBean entityManagerFactorySecondary(EntityManagerFactoryBuilder build) {
        return build.dataSource(secondaryDataSource).
                packages("com.lance.server.secondary.**.model").
                persistenceUnit("secondaryPersistenceUnit").
                build();
    }

    @Bean(name = "entityManagerSecondary")
    public EntityManager entityManager(EntityManagerFactoryBuilder builder) {
        return entityManagerFactorySecondary(builder).getObject().createEntityManager();
    }

    @Bean(name = "transactionManagerSecondary")
    public PlatformTransactionManager transactionManagerPrimary(EntityManagerFactoryBuilder builder) {
        return new JpaTransactionManager(entityManagerFactorySecondary(builder).getObject());
    }

    /***
     * Mybatics 连接池
     * @author Lance [email protected]
     * @date 2019-09-21 11:58
     * @param
     * @return org.apache.ibatis.session.SqlSessionFactory
     *
     * */
    @Bean(name = "secondarySqlSessionFactory")
    public SqlSessionFactory secondarySqlSessionFactory(@Qualifier("secondaryDataSource") DataSource dataSource) throws Exception {
        SqlSessionFactoryBean sqlSessionFactoryBean = new SqlSessionFactoryBean();
        sqlSessionFactoryBean.setDataSource(dataSource);
        sqlSessionFactoryBean.setMapperLocations(
                new PathMatchingResourcePatternResolver().getResources("classpath:mapper/secondary/**/*.xml"));
        return sqlSessionFactoryBean.getObject();
    }

    /***
     * Mybatics 事务控制
     * @author Lance [email protected]
     * @date 2019-09-21 11:58
     * @param
     * @return org.springframework.jdbc.datasource.DataSourceTransactionManager
     *
     * */
    @Bean(name = "secondaryDataSourceTransactionManager")
    public DataSourceTransactionManager secondaryDataSourceTransactionManager(@Qualifier("secondaryDataSource") DataSource dataSource) {
        return new DataSourceTransactionManager(dataSource);
    }

    /***
     * mybatics 模板
     * @author Lance [email protected]
     * @date 2019-09-21 11:57
     * @param sqlSessionFactory
     * @return org.mybatis.spring.SqlSessionTemplate
     *
     * */
    @Bean(name = "secondarySqlSessionTemplate")
    public SqlSessionTemplate secondarySqlSessionTemplate(@Qualifier("secondarySqlSessionFactory") SqlSessionFactory sqlSessionFactory) {
        return new SqlSessionTemplate(sqlSessionFactory);
    }
}

你可能感兴趣的:(SpringBoot,SpringBoot,Mybatics,JPA,多数据库,多数据源)