Springboot多数据源+Jpa配置

随着业务复杂程度的增加,单一数据源越来越不满足具体的业务逻辑以及实现。

这里我用到了MySQL和Presto两种数据源:
在这里插入图片描述
在这里插入图片描述
多数据源配置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 在使用的时候可以采用这种方式:

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

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

因我的项目中只需要使用jpa连接MySQL,所以是单数据源的Jpa配置:

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不需要其他配置,直接开始写Repository接口即可:

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

网上有很多jpa配置多数据源的文章,例如:

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

我使用上面文章介绍的方法,将MySQL单数据源配置了成Primary主数据源,反而出现很多报错,目前还不清楚报错的原因。

猜你喜欢

转载自blog.csdn.net/weixin_44455388/article/details/122339999