Springboot multiple data sources + Jpa configuration

With the increase of business complexity, a single data source is increasingly unsatisfactory for specific business logic and implementation.

Here I used two data sources, MySQL and Presto:
insert image description here
insert image description here
Multiple data source configuration GlobalDataSourceConfiguration:

@Configuration
public class GlobalDataSourceConfiguration {
    @Bean(name = "prestoDataSource")
    @ConfigurationProperties(prefix = "spring.datasource.presto")
    public DataSource prestoDataSource() {
        return DataSourceBuilder.create().build();
    }

    @Bean(name = "mysqlDataSource")
    @Primary
    @ConfigurationProperties(prefix = "spring.datasource.mysql")
    public DataSource mysqlDataSource() {
        return DataSourceBuilder.create().build();
    }

    @Bean(name = "prestoTemplate")
    public JdbcTemplate prestoJdbcTemplate(@Qualifier("prestoDataSource") DataSource prestoDataSource) {
        return new JdbcTemplate(prestoDataSource);
    }

    @Bean(name = "mysqlTemplate")
    public JdbcTemplate mysqlJdbcTemplate(@Qualifier("mysqlDataSource") DataSource mysqlDataSource) {
        return new JdbcTemplate(mysqlDataSource);
    }
}

JdbcTemplate can be used in this way:

@Autowired
@Qualifier("prestoTemplate")
private JdbcTemplate prestoTemplate;

@Autowired
@Qualifier("mysqlTemplate")
private JdbcTemplate mysqlTemplate;

Because I only need to use jpa to connect to MySQL in my project, it is a single data source Jpa configuration:

spring.jpa.database=MySQL
spring.jpa.hibernate.ddl-auto=create-drop
spring.jpa.show-sql=false
spring.jpa.open-in-view=false
spring.jpa.properties.hibernate.hbm2ddl.auto=update
spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.MySQL5InnoDBDialect

JPA with a single data source does not require other configurations, just start writing the Repository interface directly:

@Repository
public interface JobEntityRepository extends JpaRepository<JobEntity,Long> {
     JobEntity getById(Integer id);
     Page<JobEntity> findAll(Specification<Model> sp, Pageable pageable);
}

There are many articles about jpa configuring multiple data sources on the Internet, for example:

https://www.cnblogs.com/ll409546297/p/10496346.html
https://blog.csdn.net/lianghecai52171314/article/details/106724531/

I used the method introduced in the above article to configure the MySQL single data source as the Primary main data source, but many errors were reported. It is not clear why the errors are reported.

おすすめ

転載: blog.csdn.net/weixin_44455388/article/details/122339999