美文网首页SpringBoot
Spring Boot JPA多数据源配置及使用

Spring Boot JPA多数据源配置及使用

作者: iGroove | 来源:发表于2019-11-18 16:09 被阅读0次

Tips:
springboot版本:2.0.8.RELEASE
jdk:1.8

Spring Boot Jpa 在1.x和2.x中配置数据源存在很多差异,只需要配置好数据源,再配置Jpa即可使用多数据源。亲测可用~

1.依赖关系和yml
pom.xml

<!--JPA-->
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
    <groupId>mysql</groupId>
    <artifactId>mysql-connector-java</artifactId>
    <version>8.0.16</version>
</dependency>
<dependency>
    <groupId>org.projectlombok</groupId>
    <artifactId>lombok</artifactId>
    <optional>true</optional>
</dependency>

application.yml

spring:
  datasource:
    url: jdbc:mysql://localhost:3306/springboot?useUnicode=true&useSSL=false&serverTimezone=UTC
    username: root
    password: 123456
    driver-class-name: com.mysql.cj.jdbc.Driver
    primary:
      url: jdbc:mysql://localhost:3306/test1?useUnicode=true&useSSL=false&serverTimezone=UTC
      username: root
      password: 123456
      driver-class-name: com.mysql.cj.jdbc.Driver
    secondary:
      url: jdbc:mysql://localhost:3306/test2?useUnicode=true&useSSL=false&serverTimezone=UTC
      username: root
      password: 123456
      driver-class-name: com.mysql.cj.jdbc.Driver
    hikari:
      connection-timeout: 20000
      maximum-pool-size: 5
  jpa:
    hibernate:
      ddl-auto: create
    show-sql: true
logging:
  level:
    org.hibernate.type.descriptor.sql.BasicBinder: trace

指定mysql创建为innodb引擎,在resources下创建hibernate.properties,写入hibernate.dialect.storage_engine=innodb即可。

  1. 配置DataSource
@Slf4j
@Configuration
public class DataSourceConfig {
    @Bean
    @Primary
    @ConfigurationProperties("spring.datasource.primary")
    public DataSourceProperties primaryDataSourceProperties() {
        return new DataSourceProperties();
    }

    @Bean
    @Primary
    public DataSource primaryDataSource() {
        DataSourceProperties dataSourceProperties = primaryDataSourceProperties();
        log.info("\n primary datasource: {}", dataSourceProperties.getUrl());
        return dataSourceProperties.initializeDataSourceBuilder().build();
    }

    @Bean
    @ConfigurationProperties("spring.datasource.secondary")
    public DataSourceProperties secondaryDataSourceProperties() {
        return new DataSourceProperties();
    }

    @Bean
    public DataSource secondaryDataSource() {
        DataSourceProperties dataSourceProperties = secondaryDataSourceProperties();
        log.info("\n secondary datasource: {}", dataSourceProperties.getUrl());
        return dataSourceProperties.initializeDataSourceBuilder().build();
    }
}

若需要使用jdbcTemplate,加上如下jdbcTemplate配置和事务管理器即可。异常回滚需要指定事务管理器@Transactional(value="primaryTxManager")

@Bean
@Primary
public JdbcTemplate primaryJdbcTemplate(@Qualifier("primaryDataSource") DataSource dataSource) {
    return new JdbcTemplate(dataSource);
}

@Bean
@Primary
public PlatformTransactionManager primaryTxManager(@Qualifier("primaryDataSource") DataSource primaryDataSource) {
    return new DataSourceTransactionManager(primaryDataSource);
}

@Bean
public JdbcTemplate secondaryJdbcTemplate(@Qualifier("secondaryDataSource") DataSource dataSource) {
    return new JdbcTemplate(dataSource);
}

@Bean
public PlatformTransactionManager secondaryTxManager(@Qualifier("secondaryDataSource") DataSource secondaryDataSource) {
    return new DataSourceTransactionManager(secondaryDataSource);
}
  1. 配置Jpa
primaryConfig
@Configuration
@EnableTransactionManagement
@EnableJpaRepositories(
        // repository包名  替换为自己的repository路径
        basePackages = "com.xxx.xxx.repository.primary",
        // 实体管理bean名称
        entityManagerFactoryRef = "primaryEntityManagerFactory",
        // 事务管理bean名称
        transactionManagerRef = "primaryTransactionManager"
)
public class PrimaryConfig {
    @Bean
    @ConfigurationProperties(prefix = "spring.jpa")
    public JpaProperties jpaProperties() {
        return new JpaProperties();
    }

    @Primary
    @Bean(name = "primaryEntityManagerFactory")
    public LocalContainerEntityManagerFactoryBean entityManagerFactory(@Qualifier("primaryDataSource") DataSource primaryDataSource
            , JpaProperties jpaProperties, EntityManagerFactoryBuilder builder) {
        return builder
                // 设置数据源
                .dataSource(primaryDataSource)
                // 设置jpa配置
                .properties(jpaProperties.getProperties())
                // 设置hibernate配置
                .properties(jpaProperties.getHibernateProperties(new HibernateSettings()))
                // 设置实体包名  替换为自己的
                .packages("com.xxx.xxx.po")
                // 设置持久化单元名,用于@PersistenceContext注解获取EntityManager时指定数据源
                .persistenceUnit("primaryPersistenceUnit")
                .build();
    }

    @Primary
    @Bean(name = "primaryEntityManager")
    public EntityManager entityManager(@Qualifier("primaryEntityManagerFactory") EntityManagerFactory factory) {
        return factory.createEntityManager();
    }

    @Primary
    @Bean(name = "primaryTransactionManager")
    public PlatformTransactionManager transactionManager(@Qualifier("primaryEntityManagerFactory") EntityManagerFactory factory) {
        return new JpaTransactionManager(factory);
    }
}

secondaryConfig
@Configuration
@EnableTransactionManagement
@EnableJpaRepositories(
        basePackages = "com.xxx.xxx.repository.secondary",
        entityManagerFactoryRef = "secondaryEntityManagerFactory",
        transactionManagerRef = "secondaryTransactionManager"
)
public class SecondaryConfig {
    @Bean(name = "secondaryEntityManagerFactory")
    public LocalContainerEntityManagerFactoryBean entityManagerFactory(@Qualifier("secondaryDataSource") DataSource secondaryDataSource
            ,JpaProperties jpaProperties, EntityManagerFactoryBuilder builder) {
        return builder
                .dataSource(secondaryDataSource)
                .properties(jpaProperties.getProperties())
                .properties(jpaProperties.getHibernateProperties(new HibernateSettings()))
                .packages("com.xxx.xxx.po")
                .persistenceUnit("secondaryPersistenceUnit")
                .build();
    }

    @Bean(name = "secondaryEntityManager")
    public EntityManager entityManager(@Qualifier("secondaryEntityManagerFactory") EntityManagerFactory factory) {
        return factory.createEntityManager();
    }

    @Bean(name = "secondaryTransactionManager")
    public PlatformTransactionManager transactionManager(@Qualifier("secondaryEntityManagerFactory") EntityManagerFactory factory) {
        return new JpaTransactionManager(factory);
    }
}
  1. 自己创建实体和repository操作体验,repository需要放在jpa配置的包路径下,如com.xxx.xxx.repository.primary.xxxRepository,具体按实际情况修改。

相关文章

网友评论

    本文标题:Spring Boot JPA多数据源配置及使用

    本文链接:https://www.haomeiwen.com/subject/dpdbictx.html