Two datasources, two repositories in Spring Boot 2.2.0

mate00 :

I checked blog posts, tutorials, peoples' repositories, but nothing helps. Here's what I have:

There are two Docker containers with MySQL databases: ebooks and sec. Both containers are up, databases are visible, I can query the tables.

I want to have two datasources in my project: one for ebooks and one for Spring Security tables.

I wrote a simple CommandLineRunner in which I just autowire both repositories and check their sizes.

When I run my application, I get:

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

But if I run this without a second datasource and using regular Spring's autoconfiguration, table BOOKS is "seen" and I can query it.

So here is my 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

My entity classes are tiny:

@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
}

These classes are in different packages.

Repositories, again, nothing fancy:


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

Similarly with books, so I won't paste it.

And here are configuration classes:

@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;
    }
}

And second one in a separate class:

@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;
    }

}

Entrypoint class has no annotations except @SpringBootApplication.

Here is 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()
}
mate00 :

Oh my... What was missing there was an @Entity annotation with table name. So:

@Entity(name = "book")

// ... and

@Entity(name = "role")

plus proper @Column annotation with relevant column names. I'm attaching a link to my small repo where I put a working example: https://github.com/mate0021/two_datasources.git

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=129838&siteId=1