欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

Spring data jpa 配置多数据源

程序员文章站 2022-03-10 21:53:38
一、数据源配置文件AlertDbConfig@Configuration@EnableTransactionManagement@EnableJpaRepositories( entityManagerFactoryRef = "entityManagerFactoryAlert", transactionManagerRef = "transactionManagerAlert", basePackages = {"com.dianhun.multi...

一、数据源配置文件

AlertDbConfig

@Configuration
@EnableTransactionManagement
@EnableJpaRepositories(
        entityManagerFactoryRef = "entityManagerFactoryAlert",
        transactionManagerRef = "transactionManagerAlert",
        basePackages = {"com.dianhun.multipledatasources.repository.alert"})
public class AlertDbConfig {
    @Autowired
    @Qualifier("alertDataSource")
    private DataSource alertDataSource;

    @Autowired
    private JpaProperties jpaProperties;

    @Autowired
    private HibernateProperties hibernateProperties;

    @Bean(name = "entityManagerAlert")
    public EntityManager entityManagerAlert(EntityManagerFactoryBuilder builder) {
        return entityManagerFactoryAlert(builder).getObject().createEntityManager();
    }

    @Bean(name = "entityManagerFactoryAlert")
    public LocalContainerEntityManagerFactoryBean entityManagerFactoryAlert(EntityManagerFactoryBuilder builder) {
        return builder
                .dataSource(alertDataSource)
                .packages("com.dianhun.multipledatasources.model.alert")
                .persistenceUnit("alertPersistenceUnit")
                .properties(getVendorProperties())
                .build();
    }

    private Map<String, Object> getVendorProperties() {
        return hibernateProperties.determineHibernateProperties(jpaProperties.getProperties(), new HibernateSettings());
    }

    @Bean(name = "transactionManagerAlert")
    public PlatformTransactionManager transactionManagerAlert(EntityManagerFactoryBuilder builder) {
        return new JpaTransactionManager(entityManagerFactoryAlert(builder).getObject());
    }
}

AppDbConfig

@Configuration
@EnableTransactionManagement
@EnableJpaRepositories(
        entityManagerFactoryRef = "entityManagerFactoryApp",
        transactionManagerRef = "transactionManagerApp",
        basePackages = {"com.dianhun.multipledatasources.repository.app"})
public class AppDbConfig {
    @Autowired
    @Qualifier("appDataSource")
    private DataSource appDataSource;

    @Autowired
    private JpaProperties jpaProperties;

    @Autowired
    private HibernateProperties hibernateProperties;

    @Primary
    @Bean(name = "entityManagerApp")
    public EntityManager entityManager(EntityManagerFactoryBuilder builder) {
        return entityManagerFactoryApp(builder).getObject().createEntityManager();
    }

    @Primary
    @Bean(name = "entityManagerFactoryApp")
    public LocalContainerEntityManagerFactoryBean entityManagerFactoryApp(EntityManagerFactoryBuilder builder) {
        return builder
                .dataSource(appDataSource)
                .packages("com.dianhun.multipledatasources.model.app")
                .persistenceUnit("appPersistenceUnit")
                .properties(getVendorProperties())
                .build();
    }

    private Map<String, Object> getVendorProperties() {
        return hibernateProperties.determineHibernateProperties(jpaProperties.getProperties(), new HibernateSettings());
    }

    @Primary
    @Bean(name = "transactionManagerApp")
    public PlatformTransactionManager transactionManagerApp(EntityManagerFactoryBuilder builder) {
        return new JpaTransactionManager(entityManagerFactoryApp(builder).getObject());
    }
}

DataSourceConfig

@Configuration
public class DataSourceConfig {

    @Bean
    @Primary
    @ConfigurationProperties("com.dianhun.sharding.datasource.app")
    public DataSourceProperties appDataSourceProperties() {
        return new DataSourceProperties();
    }

    @Bean
    @Primary
    @ConfigurationProperties("com.dianhun.sharding.datasource.app.configuration")
    public HikariDataSource appDataSource() {
        return appDataSourceProperties().initializeDataSourceBuilder().type(HikariDataSource.class).build();
    }

    @Bean
    @ConfigurationProperties("com.dianhun.sharding.datasource.alert")
    public DataSourceProperties alertDataSourceProperties() {
        return new DataSourceProperties();
    }

    @Bean
    @ConfigurationProperties("com.dianhun.sharding.datasource.alert.configuration")
    public HikariDataSource alertDataSource() {
        return alertDataSourceProperties().initializeDataSourceBuilder().type(HikariDataSource.class).build();
    }
}

二、项目配置文件

spring:
  jpa:
    show-sql: true
com:
  dianhun:
    sharding:
      datasource:
        app:
          url: jdbc:mysql://127.0.0.1:3309/multipledatasources?useUnicode=true&characterEncoding=utf-8&serverTimezone=GMT%2b8&zeroDateTimeBehavior=convertToNull
          username: root
          password: 123456
          driver-class-name: com.mysql.cj.jdbc.Driver
          configuration:
            maximum-pool-size: 30
        alert:
          url: jdbc:mysql://127.0.0.1:3310/multipledatasources?useUnicode=true&characterEncoding=utf-8&serverTimezone=GMT%2b8&zeroDateTimeBehavior=convertToNull
          username: root
          password: 123456
          driver-class-name: com.mysql.cj.jdbc.Driver
          configuration:
            maximum-pool-size: 30
logging:
  level:
    root: INFO

三、实体类和接口文件

AppEntity

@DynamicInsert
@DynamicUpdate
@EqualsAndHashCode()
@Entity
@Data
@AllArgsConstructor
@NoArgsConstructor
@Table(name = "app", schema = "multipledatasources", catalog = "")
public class AppEntity {
    @Id
    @Column(name = "id", nullable = false)
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Integer id;
    private String name;
}


@Repository
public interface AppRepository extends JpaRepository<AppEntity, Integer> {
}

三、测试文件

@RunWith(SpringRunner.class)
@SpringBootTest
public class MultipleDataSourcesApplicationTest {
    @Autowired
    AppRepository repository;
    @Autowired
    AlertRepository alertRepository;

    @Test
    public void testApp() {
        repository.save(new AppEntity(1, "app"));
    }

    @Test
    public void testAlert() {
        alertRepository.save(new AlertEntity(2, "testAlert"));
    }
}

本文地址:https://blog.csdn.net/qq_41291945/article/details/111974732