BAEL-5323: Spring Boot with multiple data sources (#11741)

* BAEL-5323: Spring Boot with multiple data sources

* BAEL-5323: small fixes

* BAEL-5323: fix test class

* BAEL-5323: Refactor configuration classes

* BAEL-5323: Set proeprty to private

* BAEL-5323: rename test class to follow naming conventions
This commit is contained in:
Ralf Ueberfuhr 2022-02-04 17:58:16 +01:00 committed by GitHub
parent b9174fb3f4
commit 9a8d9227b7
14 changed files with 369 additions and 0 deletions

View File

@ -52,6 +52,7 @@
<module>spring-boot-libraries</module>
<module>spring-boot-libraries-2</module>
<module>spring-boot-logging-log4j2</module>
<module>spring-boot-multiple-datasources</module>
<module>spring-boot-mvc</module>
<module>spring-boot-mvc-2</module>
<module>spring-boot-mvc-3</module>

View File

@ -0,0 +1 @@
.local-db

View File

@ -0,0 +1,58 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<artifactId>spring-boot-multiple-datasources</artifactId>
<version>0.1.0-SNAPSHOT</version>
<name>spring-boot-multiple-datasources</name>
<packaging>jar</packaging>
<description>Module For Spring Boot With Multiple Datasources</description>
<parent>
<groupId>com.baeldung.spring-boot-modules</groupId>
<artifactId>spring-boot-modules</artifactId>
<version>1.0.0-SNAPSHOT</version>
<relativePath>../pom.xml</relativePath>
</parent>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>com.h2database</groupId>
<artifactId>h2</artifactId>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
<scope>runtime</scope>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
<properties>
<spring-boot.version>2.6.3</spring-boot.version>
</properties>
</project>

View File

@ -0,0 +1,13 @@
package com.baeldung.spring.datasources;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class MultipleDatasourcesApplication {
public static void main(String[] args) {
SpringApplication.run(MultipleDatasourcesApplication.class, args);
}
}

View File

@ -0,0 +1,48 @@
package com.baeldung.spring.datasources.todos;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
@Entity
public class Todo {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
private String title;
private boolean completed;
public Todo() {
}
public Todo(String title) {
this.title = title;
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public boolean isCompleted() {
return completed;
}
public void setCompleted(boolean completed) {
this.completed = completed;
}
}

View File

@ -0,0 +1,28 @@
package com.baeldung.spring.datasources.todos;
import org.springframework.boot.autoconfigure.jdbc.DataSourceProperties;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import javax.sql.DataSource;
@Configuration
public class TodoDatasourceConfiguration {
@Bean
@ConfigurationProperties("spring.datasource.todos")
public DataSourceProperties todosDataSourceProperties() {
return new DataSourceProperties();
}
@Bean
@Primary
public DataSource todosDataSource() {
return todosDataSourceProperties()
.initializeDataSourceBuilder()
.build();
}
}

View File

@ -0,0 +1,40 @@
package com.baeldung.spring.datasources.todos;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.orm.jpa.EntityManagerFactoryBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
import org.springframework.orm.jpa.JpaTransactionManager;
import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.annotation.EnableTransactionManagement;
import javax.sql.DataSource;
import java.util.Objects;
@Configuration
@EnableTransactionManagement
@EnableJpaRepositories(
basePackageClasses = Todo.class,
entityManagerFactoryRef = "todosEntityManagerFactory",
transactionManagerRef = "todosTransactionManager"
)
public class TodoJpaConfiguration {
@Bean
public LocalContainerEntityManagerFactoryBean todosEntityManagerFactory(
@Qualifier("todosDataSource") DataSource dataSource,
EntityManagerFactoryBuilder builder) {
return builder
.dataSource(dataSource)
.packages(Todo.class)
.build();
}
@Bean
public PlatformTransactionManager todosTransactionManager(
@Qualifier("todosEntityManagerFactory") LocalContainerEntityManagerFactoryBean todosEntityManagerFactory) {
return new JpaTransactionManager(Objects.requireNonNull(todosEntityManagerFactory.getObject()));
}
}

View File

@ -0,0 +1,6 @@
package com.baeldung.spring.datasources.todos;
import org.springframework.data.jpa.repository.JpaRepository;
public interface TodoRepository extends JpaRepository<Todo, Long> {
}

View File

@ -0,0 +1,39 @@
package com.baeldung.spring.datasources.topics;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
@Entity
public class Topic {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
private String title;
public Topic() {
}
public Topic(String title) {
this.title = title;
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
}

View File

@ -0,0 +1,26 @@
package com.baeldung.spring.datasources.topics;
import org.springframework.boot.autoconfigure.jdbc.DataSourceProperties;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import javax.sql.DataSource;
@Configuration
public class TopicDatasourceConfiguration {
@Bean
@ConfigurationProperties("spring.datasource.topics")
public DataSourceProperties topicsDataSourceProperties() {
return new DataSourceProperties();
}
@Bean
public DataSource topicsDataSource() {
return topicsDataSourceProperties()
.initializeDataSourceBuilder()
.build();
}
}

View File

@ -0,0 +1,41 @@
package com.baeldung.spring.datasources.topics;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.orm.jpa.EntityManagerFactoryBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
import org.springframework.orm.jpa.JpaTransactionManager;
import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.annotation.EnableTransactionManagement;
import javax.sql.DataSource;
import java.util.Objects;
@Configuration
@EnableTransactionManagement
@EnableJpaRepositories(
basePackageClasses = Topic.class,
entityManagerFactoryRef = "topicsEntityManagerFactory",
transactionManagerRef = "topicsTransactionManager"
)
public class TopicJpaConfiguration {
@Bean
public LocalContainerEntityManagerFactoryBean topicsEntityManagerFactory(
@Qualifier("topicsDataSource") DataSource dataSource,
EntityManagerFactoryBuilder builder
) {
return builder
.dataSource(dataSource)
.packages(Topic.class)
.build();
}
@Bean
public PlatformTransactionManager topicsTransactionManager(
@Qualifier("topicsEntityManagerFactory") LocalContainerEntityManagerFactoryBean topicsEntityManagerFactory) {
return new JpaTransactionManager(Objects.requireNonNull(topicsEntityManagerFactory.getObject()));
}
}

View File

@ -0,0 +1,6 @@
package com.baeldung.spring.datasources.topics;
import org.springframework.data.jpa.repository.JpaRepository;
public interface TopicRepository extends JpaRepository<Topic, Long> {
}

View File

@ -0,0 +1,23 @@
spring:
datasource:
todos:
url: jdbc:h2:./.local-db/todos;DB_CLOSE_DELAY=-1;MODE=DB2;AUTO_SERVER=TRUE
username: sa
password: null
driverClassName: org.h2.Driver
topics:
url: jdbc:h2:./.local-db/topics;DB_CLOSE_DELAY=-1;MODE=DB2;AUTO_SERVER=TRUE
username: sa
password: null
driverClassName: org.h2.Driver
h2:
console:
enabled: true
path: /h2-console
jpa:
generate-ddl: true
hibernate:
ddl-auto: update
properties:
hibernate:
dialect: org.hibernate.dialect.H2Dialect

View File

@ -0,0 +1,39 @@
package com.baeldung.spring.datasources;
import com.baeldung.spring.datasources.todos.Todo;
import com.baeldung.spring.datasources.todos.TodoRepository;
import com.baeldung.spring.datasources.topics.Topic;
import com.baeldung.spring.datasources.topics.TopicRepository;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.orm.jpa.DataJpaTest;
import java.util.Optional;
import static org.assertj.core.api.Assertions.assertThat;
@DataJpaTest // no test database!
class MultipleDatasourcesIntegrationTest {
@Autowired
TodoRepository todoRepo;
@Autowired
TopicRepository topicRepo;
@Test
void shouldSaveTodoToTodoDB() {
Todo todo = new Todo("test");
Todo saved =todoRepo.save(todo);
Optional<Todo> result= todoRepo.findById(saved.getId());
assertThat(result).isPresent();
}
@Test
void shouldSaveTopicToTopicDB() {
Topic todo = new Topic("test");
Topic saved =topicRepo.save(todo);
Optional<Topic> result= topicRepo.findById(saved.getId());
assertThat(result).isPresent();
}
}