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

SpringBoot 配置多数据源(Spring JPA版)

程序员文章站 2024-03-22 19:18:10
...

第一步:创建SpringBoot项目

最终项目目录结构

SpringBoot 配置多数据源(Spring JPA版)

Maven依赖

<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>mysql</groupId>
        <artifactId>mysql-connector-java</artifactId>
        <scope>runtime</scope>
    </dependency>
    <dependency>
        <groupId>org.projectlombok</groupId>
        <artifactId>lombok</artifactId>
        <optional>true</optional>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-test</artifactId>
        <scope>test</scope>
        <exclusions>
            <exclusion>
                <groupId>org.junit.vintage</groupId>
                <artifactId>junit-vintage-engine</artifactId>
            </exclusion>
        </exclusions>
    </dependency>

application.yml

server:
  port: 80
  servlet:
    context-path: /mds
spring:
  datasource:
    test1:
      driverClassName: com.mysql.cj.jdbc.Driver
      # url必须使用jdbc-url的名称
      jdbc-url: jdbc:mysql://localhost:3306/db_test?useSSL=false&serverTimezone=UTC&user=root&password=&useUnicode=true&characterEncoding=UTF8&autoReconnect=true&failOverReadOnly=false&allowPublicKeyRetrieval=true
      password: root
      username: root
    test2:
      driverClassName: com.mysql.cj.jdbc.Driver
      jdbc-url: jdbc:mysql://localhost:3306/test?useSSL=false&serverTimezone=UTC&user=root&password=&useUnicode=true&characterEncoding=UTF8&autoReconnect=true&failOverReadOnly=false&allowPublicKeyRetrieval=true
      password: root
      username: root
  jpa:
    hibernate:
      ddl-auto: update #如果再次运行,检查表是否要更新
    properties:
      hibernate:
        enable_lazy_load_no_trans: true
    show-sql: true
    database: mysql
    open-in-view: false
    database-platform: org.hibernate.dialect.MySQL5InnoDBDialect
    generate-ddl: false

第二步:创建实体类

@Data
@Entity
@Table(name = "tb_dept")
public class Dept {
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Integer deptno;
    @Column
    private String dname;
    @Column
    private String loc;
}

第三步:创建Dao

在com.hc.test1.dao包下创建DeptDao1.java

public interface DeptDao1 extends JpaRepository<Dept,Integer> {
}

在com.hc.test1.dao包下创建DeptDao2.java

public interface DeptDao2 extends JpaRepository<Dept,Integer> {
}

第四步:配置数据源

DataSourceConfig

@Configuration
public class DataSourceConfig {
    @Primary  //表示当某一个类存在多个实例时,优先使用哪个实例
    @Bean(name = "test1DataSource")
    @ConfigurationProperties(prefix="spring.datasource.test1")
    public DataSource test1DataSource() {
        return DataSourceBuilder.create().build();
    }
    @Bean(name = "test2DataSource")
    @ConfigurationProperties(prefix="spring.datasource.test2")
    public DataSource test2DataSource() {
        return DataSourceBuilder.create().build();
    }
}

Test1DataSourceConfig

@Configuration
@EnableTransactionManagement
@EnableJpaRepositories(
        entityManagerFactoryRef = "test1EntityManagerFactory",//实体管理
        transactionManagerRef = "test1TransactionManager", //事务管理
        basePackages = "com.hc.test1.dao") //设置Repository所在位置
public class Test1DataSourceConfig {
    //数据源
    @Resource(name = "test1DataSource")
    private DataSource dataSource;
    // JPA其它参数设置,其数据在application.properties中配置
    @Resource
    private JpaProperties jpaProperties;
    //实体管理工厂builder
    @Resource
    private EntityManagerFactoryBuilder builder;
    //配置实体管理工厂的Bean
    @Primary
    @Bean(name = "test1EntityManagerFactory")
    public LocalContainerEntityManagerFactoryBean test1EntityManagerFactoryBean() {
        return builder.dataSource(dataSource)
                //加入jpa的其他配置参数比如(ddl-auto: update等)
                .properties(jpaProperties.getProperties())
                //相当于给这个配置取一个别名
                .persistenceUnit("test1PersistenceUnit")
                //设置这个数据源对应的实体类所在位置
                .packages("com.hc.bean")
                .build();
    }
    // EntityManager不过解释,用过jpa的应该都了解
    @Primary
    @Bean(name = "test1EntityManager")
    public EntityManager entityManager() {
        return test1EntityManagerFactoryBean().getObject().createEntityManager();
    }
    @Bean(name = "test1TransactionManager")
    public PlatformTransactionManager test1TransactionManager(EntityManagerFactoryBuilder builder) {
        return new JpaTransactionManager(test1EntityManagerFactoryBean().getObject());
    }
}

Test2DataSourceConfig

@Configuration
@EnableTransactionManagement
@EnableJpaRepositories(
        entityManagerFactoryRef = "test2EntityManagerFactory",//实体管理
        transactionManagerRef = "test2TransactionManager", //事务管理
        basePackages = "com.hc.test2.dao") //设置Repository所在位置
public class Test2DataSourceConfig {
    //数据源
    @Resource(name = "test2DataSource")
    private DataSource dataSource;
    // JPA其它参数设置, 其数据在application.properties中配置
    @Resource
    private JpaProperties jpaProperties;
    //实体管理工厂builder
    @Resource
    private EntityManagerFactoryBuilder builder;
    //配置实体管理工厂的Bean
    @Bean(name = "test2EntityManagerFactory")
    public LocalContainerEntityManagerFactoryBean test2EntityManagerFactoryBean() {
        return builder.dataSource(dataSource)
                //加入jpa的其他配置参数比如(ddl-auto: update等)
                .properties(jpaProperties.getProperties())
                //相当于给这个配置取一个别名
                .persistenceUnit("test2PersistenceUnit")
                //设置这个数据源对应的实体类所在位置
                .packages("com.hc.bean")
                .build();
    }
    // EntityManager不过解释,用过jpa的应该都了解
    @Bean(name = "test2EntityManager")
    public EntityManager entityManager() {
        return test2EntityManagerFactoryBean().getObject().createEntityManager();
    }
    @Bean(name = "test2TransactionManager")
    public PlatformTransactionManager test2TransactionManager(EntityManagerFactoryBuilder builder) {
        return new JpaTransactionManager(test2EntityManagerFactoryBean().getObject());
    }
}

第五步:测试代码

DeptDaoTest

@SpringBootTest
class DeptDao1Test {
    @Resource
    private DeptDao1 deptDao1;
    @Test
    public void fun(){
        List<Dept> depts = deptDao1.findAll();
        depts.forEach(System.out::println);
    }
}

DeptDao2Test

@SpringBootTest
class DeptDao2Test {
    @Resource
    private DeptDao2 deptDao2;
    @Test
    public void findAll(){
        deptDao2.findAll().forEach(System.out::println);
    }
}