Spring Boot2 series of tutorials (twenty-five) Spring Boot integrate multiple data sources Jpa

This article is the last one Spring Boot integrate data persistence solutions, mainly to talk to everyone and multi-source data integration issues Spring Boot Jpa. In Spring Boot integration JbdcTemplate multiple data sources, Spring Boot integrate multiple data sources MyBatis and Spring Boot integrate multiple data sources Jpa knowledge of these three points, the integration of multiple data sources Jpa regarded as the most complex, but also a lot of people the most when configuring easily the type of fault. This article and everyone will follow Song Ge tutorials, step by step Jpa integrate multiple data sources.

Project Creation

The first is to create a Spring Boot project, create add basic Web, Jpa and rely upon MySQL, as follows:

Once created, add Druid dependence, here and in the foregoing requirement as to the use made for the Spring Boot Druid, everyone may have found that if the integration of multiple data sources must use this dependence, because this dependence have DruidDataSourceBuilder, finally also remember to lock the database version-dependent, because most people may still use MySQL 5.x rather than 8.x. Complete reliance as follows:

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
    <groupId>com.alibaba</groupId>
    <artifactId>druid-spring-boot-starter</artifactId>
    <version>1.1.10</version>
</dependency>
<dependency>
    <groupId>mysql</groupId>
    <artifactId>mysql-connector-java</artifactId>
    <version>5.1.28</version>
    <scope>runtime</scope>
</dependency>

So after the success of the project is created.

basic configuration

In the basic configuration, we first configure multiple data sources as well as basic information DataSource, first add the following configuration information application.properties in:

#  数据源一
spring.datasource.one.username=root
spring.datasource.one.password=root
spring.datasource.one.url=jdbc:mysql:///test01?useUnicode=true&characterEncoding=UTF-8
spring.datasource.one.type=com.alibaba.druid.pool.DruidDataSource

#  数据源二
spring.datasource.two.username=root
spring.datasource.two.password=root
spring.datasource.two.url=jdbc:mysql:///test02?useUnicode=true&characterEncoding=UTF-8
spring.datasource.two.type=com.alibaba.druid.pool.DruidDataSource

# Jpa配置
spring.jpa.properties.database=mysql
spring.jpa.properties.show-sql=true
spring.jpa.properties.database-platform=mysql
spring.jpa.properties.hibernate.ddl-auto=update
spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.MySQL57Dialect

Here Jpa disposed above and compared to the same key in the multi-Properties, configuration of multiple data sources and foregoing, and then the next two the DataSource configuration, as follows:

@Configuration
public class DataSourceConfig {
    @Bean
    @ConfigurationProperties(prefix = "spring.datasource.one")
    @Primary
    DataSource dsOne() {
        return DruidDataSourceBuilder.create().build();
    }
    @Bean
    @ConfigurationProperties(prefix = "spring.datasource.two")
    DataSource dsTwo() {
        return DruidDataSourceBuilder.create().build();
    }
}

Multi data source configuration where the configuration of the foregoing and are basically the same, but pay attention to the use of more than a few notes @Primary in Spring, this comment must not be less, or at the start of the project to be wrong, @ Primary means that when a certain class when there are multiple instances, the use of which instance priority.

Okay, so, DataSource there.

Multiple Data Source Configuration

Next, the configuration of the basic information Jpa, where two data sources, respectively, in two classes I to configure, first look at the first configuration:

@Configuration
@EnableJpaRepositories(basePackages = "org.javaboy.jpa.dao",entityManagerFactoryRef = "localContainerEntityManagerFactoryBeanOne",transactionManagerRef = "platformTransactionManagerOne")
public class JpaConfigOne {
    @Autowired
    @Qualifier(value = "dsOne")
    DataSource dsOne;
    @Autowired
    JpaProperties jpaProperties;
    @Bean
    @Primary
    LocalContainerEntityManagerFactoryBean localContainerEntityManagerFactoryBeanOne(EntityManagerFactoryBuilder builder) {
        return builder.dataSource(dsOne)
                .packages("org.javaboy.jpa.model")
                .properties(jpaProperties.getProperties())
                .persistenceUnit("pu1")
                .build();
    }
    @Bean
    PlatformTransactionManager platformTransactionManagerOne(EntityManagerFactoryBuilder builder) {
        LocalContainerEntityManagerFactoryBean factoryBeanOne = localContainerEntityManagerFactoryBeanOne(builder);
        return new JpaTransactionManager(factoryBeanOne.getObject());
    }
}

First, here injection dsOne, then into JpaProperties, JpaProperties is an example provided by the system, the data is inside jpa related configuration we configured in application.properties in. Then we offer two Bean, are LocalContainerEntityManagerFactoryBean and PlatformTransactionManager transaction manager, unlike MyBatis and JdbcTemplate, in Jpa, the transaction must be configured. When LocalContainerEntityManagerFactoryBean provided, the need to specify the packages, the position where the packages of this package is the specified data source where the corresponding entity class, Also in the configuration class herein designated position located by @EnableJpaRepositories dao annotations, and respectively correspond LocalContainerEntityManagerFactoryBean and PlatformTransactionManager the name references.

Okay, so the first one configured, second base and the similar, there are a few differences:

  • Dao different locations
  • Different persistenceUnit
  • Different names related to the bean

Note that the entity class can be shared.

code show as below:

@Configuration
@EnableJpaRepositories(basePackages = "org.javaboy.jpa.dao2",entityManagerFactoryRef = "localContainerEntityManagerFactoryBeanTwo",transactionManagerRef = "platformTransactionManagerTwo")
public class JpaConfigTwo {
    @Autowired
    @Qualifier(value = "dsTwo")
    DataSource dsTwo;
    @Autowired
    JpaProperties jpaProperties;
    @Bean
    LocalContainerEntityManagerFactoryBean localContainerEntityManagerFactoryBeanTwo(EntityManagerFactoryBuilder builder) {
        return builder.dataSource(dsTwo)
                .packages("org.javaboy.jpa.model")
                .properties(jpaProperties.getProperties())
                .persistenceUnit("pu2")
                .build();
    }
    @Bean
    PlatformTransactionManager platformTransactionManagerTwo(EntityManagerFactoryBuilder builder) {
        LocalContainerEntityManagerFactoryBean factoryBeanTwo = localContainerEntityManagerFactoryBeanTwo(builder);
        return new JpaTransactionManager(factoryBeanTwo.getObject());
    }
}

Next, each provided at a corresponding position-related entity classes and dao to, the data source is a dao follows:

package org.javaboy.jpa.dao;
public interface UserDao extends JpaRepository<User,Integer> {
    List<User> getUserByAddressEqualsAndIdLessThanEqual(String address, Integer id);
    @Query(value = "select * from t_user where id=(select max(id) from t_user)",nativeQuery = true)
    User maxIdUser();
}

Two data sources dao follows:

package org.javaboy.jpa.dao2;
public interface UserDao2 extends JpaRepository<User,Integer> {
    List<User> getUserByAddressEqualsAndIdLessThanEqual(String address, Integer id);

    @Query(value = "select * from t_user where id=(select max(id) from t_user)",nativeQuery = true)
    User maxIdUser();
}

Common entity classes are as follows:

package org.javaboy.jpa.model;
@Entity(name = "t_user")
public class User {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Integer id;
    private String username;
    private String address;
    //省略getter/setter
}

This, even if all configuration is completed, the next injection can be in different UserDao Service, different operation of the different data sources UserDao.

In fact, the integration of multiple data sources Jpa is not too difficult, that is, there are a few details, the details of these issues resolved, in fact, more than other data sources previously described are similar throughout.

Well, this article will introduce here.

Related cases have been uploaded to GitHub, little friends are welcome to download: https://github.com/lenve/javaboy-code-samples

Song Ge scan code concerned, the public number backstage reply 2TB, Song Ge obtain exclusive ultra-dry 2TB free Java learning

Guess you like

Origin www.cnblogs.com/lenve/p/11910161.html