首页 > 解决方案 > Spring Boot 2.2.0 中的两个数据源,两个存储库

问题描述

我检查了博客文章、教程、人们的存储库,但没有任何帮助。这是我所拥有的:

有两个带有 MySQL 数据库的 Docker 容器:ebookssec. 两个容器都已启动,数据库可见,我可以查询表。

我想在我的项目中有两个数据源:一个用于电子书,一个用于 Spring Security 表。

我写了一个简单CommandLineRunner的方法,我只是自动连接两个存储库并检查它们的大小。

当我运行我的应用程序时,我得到:

Caused by: java.sql.SQLSyntaxErrorException: Table 'ebooks.Book' doesn't exist

但是,如果我在没有第二个数据源的情况下运行它并使用常规 Spring 的自动配置,则表 BOOKS 是“可见的”,我可以查询它。

所以这是我的application.properties

book.datasource.url=jdbc:mysql://172.17.0.2:3306/ebooks
book.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
book.datasource.username=someuser
book.datasource.password=somepass

security.datasource.url=jdbc:mysql://172.17.0.3:3306/sec
security.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
security.datasource.username=someuser
security.datasource.password=somepass

我的实体类很小:

@Entity
public class Book {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private int id;

    private String title;

    private String author;

    private int locations;


    public Book() {
    }

    public Book(String title, String author, int locations) {
        this.title = title;
        this.author = author;
        this.locations = locations;
    }

    public Book(int id, String title, String author, int locations) {
        this(title, author, locations);
        this.id = id;
    }

// ... getters setters and so on
}

@Entity
public class Role {

    @Id
    @GeneratedValue
    private int id;

    private String roleName;


    public Role() {
    }

    public Role(int id, String roleName) {
        this.id = id;
        this.roleName = roleName;
    }

// ... getters and setters
}

这些类位于不同的包中。

存储库,再一次,没什么特别的:


@Repository
public interface RoleRepository extends JpaRepository<Role, Integer> {
}

书籍也是如此,所以我不会粘贴它。

这里是配置类:

@Configuration
@EnableTransactionManagement
@EnableJpaRepositories(
        basePackages = "rnd.mate00.twodatasources.model1",
        entityManagerFactoryRef = "bookEntityManagerFactory",
        transactionManagerRef = "bookTransactionManager")
public class BookDatasourceConfiguration {

    @Value("${book.datasource.driver-class-name}")
    private String driver;

    @Value("${book.datasource.url}")
    private String url;

    @Value("${book.datasource.username}")
    private String user;

    @Value("${book.datasource.password}")
    private String pass;

    @Bean
    @Primary
    public DataSource bookDataSource() {
        System.out.println("Configuring book.datasources");
        DriverManagerDataSource dataSource = new DriverManagerDataSource();
        dataSource.setDriverClassName(driver);
        dataSource.setUrl(url);
        dataSource.setUsername(user);
        dataSource.setPassword(pass);

        return dataSource;
    }

    @Bean
    @Primary
    public LocalContainerEntityManagerFactoryBean bookEntityManagerFactory(EntityManagerFactoryBuilder builder) {
        return builder
                .dataSource(bookDataSource())
                .packages("rnd.mate00.twodatasources.model1")
                .persistenceUnit("booksPU")
                .build();
    }

    @Bean
    @Primary
    public TransactionManager bookTransactionManager(EntityManagerFactoryBuilder builder) {
        JpaTransactionManager manager = new JpaTransactionManager();
        manager.setDataSource(bookDataSource());
        manager.setEntityManagerFactory(bookEntityManagerFactory(builder).getObject());

        return manager;
    }
}

第二个在一个单独的类中:

@Configuration
@EnableJpaRepositories(
        basePackageClasses = { Role.class },
        entityManagerFactoryRef = "securityEntityManagerFactory",
        transactionManagerRef = "securityTransactionManager"
)
public class SecurityDatasourceConfiguration {

    @Value("${security.datasource.driver-class-name}")
    private String driver;

    @Value("${security.datasource.url}")
    private String url;

    @Value("${security.datasource.username}")
    private String user;

    @Value("${security.datasource.password}")
    private String pass;

    @Bean
    public DataSource securityDataSource() {
        System.out.println("Configuring security.datasources");
        DriverManagerDataSource dataSource = new DriverManagerDataSource();
        dataSource.setDriverClassName(driver);
        dataSource.setUrl(url);
        dataSource.setUsername(user);
        dataSource.setPassword(pass);

        return dataSource;
    }

    @Bean
    public LocalContainerEntityManagerFactoryBean securityEntityManagerFactory(EntityManagerFactoryBuilder builder) {
        return builder
                .dataSource(securityDataSource())
                .packages(Role.class)
                .persistenceUnit("securityPU")
                .build();
    }

    @Bean
    public TransactionManager securityTransactionManager(EntityManagerFactoryBuilder builder) {
        JpaTransactionManager manager = new JpaTransactionManager();
        manager.setDataSource(securityDataSource());
        manager.setEntityManagerFactory(securityEntityManagerFactory(builder).getObject());

        return manager;
    }

}

入口点类没有注释,除了@SpringBootApplication.

这里是build.gradle

plugins {
    id 'org.springframework.boot' version '2.2.0.M4'
    id 'java'
}

apply plugin: 'io.spring.dependency-management'

group = 'rnd.mate00'
version = '0.0.1-SNAPSHOT'
sourceCompatibility = '11'

repositories {
    mavenCentral()
    maven { url 'https://repo.spring.io/milestone' }
}

dependencies {
    runtime('com.h2database:h2')
    compile('mysql:mysql-connector-java')
    implementation 'org.springframework.boot:spring-boot-starter-data-jpa'
    implementation 'org.springframework.boot:spring-boot-starter-web'
    testImplementation('org.springframework.boot:spring-boot-starter-test') {
        exclude group: 'org.junit.vintage', module: 'junit-vintage-engine'
        exclude group: 'junit', module: 'junit'
    }
}

test {
    useJUnitPlatform()
}

标签: javaspring-bootspring-data-jpa

解决方案


哦,我的...缺少的是@Entity带有表名的注释。所以:

@Entity(name = "book")

// ... and

@Entity(name = "role")

@Column加上带有相关列名的适当注释。我附上了一个链接到我的小仓库,我在其中放置了一个工作示例: https ://github.com/mate0021/two_datasources.git


推荐阅读