<h2 class="wp-block-heading">Overview</h2>



<p class="wp-block-paragraph">In this article, we will explore a simple Spring Boot application to implement a simple Spring configuration for a Spring Data JPA with multiple databases requirements.</p>



<p class="wp-block-paragraph">Create an application to store information related to <strong>Books</strong> in a database named <strong>book-database</strong>. </p>



<p class="wp-block-paragraph">In the same application, we want to store information related to <strong>Author</strong> in a separate database named <strong>author-database</strong>.</p>



<p class="wp-block-paragraph">Now, create the entities for both domains:</p>



<h2 class="wp-block-heading">Entities classes</h2>



<p class="wp-block-paragraph">First, let&#8217;s create a simple entity class for the Book domain.</p>



<p class="wp-block-paragraph">Here is the first Book entity:</p>



<pre class="wp-block-code"><code>package com.dineshonjava.myapp.model.book;

@Entity
@Table(schema = "books")
public class Book {

 @Id
 @GeneratedValue(strategy = GenerationType.AUTO)
 private int bookId;

 private String title;

 private String author;

 private String publisher;

 private double price;
}</code></pre>



<p class="wp-block-paragraph">Now, let&#8217;s create a simple entity class for the Author domain.</p>



<pre class="wp-block-code"><code>package com.dineshonjava.myapp.model.author;

@Entity
@Table(schema = "authors")
public class Author {

 @Id
 private int authorId;

 private String name;

 private String email;
}</code></pre>



<p class="wp-block-paragraph">As you can see both entity classes, we have placed them in independent packages.</p>



<p class="wp-block-paragraph">Let&#8217;s create JPA repositories for both entity classes.</p>



<h2 class="wp-block-heading">The JPA Repositories</h2>



<p class="wp-block-paragraph">Let&#8217;s create a JPA repository class for the Book entity, <strong>BookRepository</strong>:</p>



<pre class="wp-block-code"><code>package com.dineshonjava.myapp.dao.book;

public interface BookRepository
 extends JpaRepository<;Book, Integer> { }</code></pre>



<p class="wp-block-paragraph">Next, let&#8217;s create another repository class for Author, <strong>AuthorRepository</strong>:</p>



<pre class="wp-block-code"><code>package com.dineshonjava.myapp.dao.author;

public interface AuthorRepository
 extends JpaRepository<;Author, Integer> { }</code></pre>



<p class="wp-block-paragraph">Again we have placed both repositories into different packages due to separate databases.</p>



<p class="wp-block-paragraph">Let&#8217;s move to create configurations for both databases using Spring Boot. We can simply add this DB configuration into an <strong>application.properties</strong> file.</p>



<p class="wp-block-paragraph">By default, Spring Boot will instantiate its default DataSource with the configuration properties prefixed by <strong><em>spring.datasource.</em></strong><em><strong>*</strong></em> but we can create separate prefixed values as well.</p>



<h2 class="wp-block-heading">Database configurations</h2>



<p class="wp-block-paragraph">Let&#8217;s add the following database configuration for the book database into the <strong>application.properties </strong>file.</p>



<pre class="wp-block-code"><code>spring.datasource.jdbcUrl = <;<;book-database-url>>
spring.datasource.username = <;<;book-database-username>>
spring.datasource.password = <;<;book-database-passwaord>></code></pre>



<p class="wp-block-paragraph">Let&#8217;s the follow configuration related to the second database using the same way to configure the second DataSource as below:</p>



<pre class="wp-block-code"><code>spring.author-datasource.jdbcUrl = <;<;author-database-url>>
spring.author-datasource.username = <;<;author-database-username>>
spring.author-datasource.password = <;<;author-database-passwaord>></code></pre>



<p class="wp-block-paragraph">Now, we need to create different Spring Boot autoconfiguration files to pick up both database configurations from the properties file as added above for two different DataSources.</p>



<h2 class="wp-block-heading">Spring Boot autoconfiguration</h2>



<p class="wp-block-paragraph">Let&#8217;s create Spring Boot autoconfiguration for the book database.</p>



<pre class="wp-block-code"><code>@Configuration
@EnableJpaRepositories(
 basePackages = "com.dineshonjava.myapp.dao.book",
 entityManagerFactoryRef = "bookEntityManager",
 transactionManagerRef = "bookTransactionManager")
public class PersistenceBookAutoConfiguration {
 
 @Primary
 @Bean
 @ConfigurationProperties(prefix="spring.datasource")
 public DataSource bookDataSource() {
 return DataSourceBuilder.create().build();
 }

 @Bean
 @Primary
 public LocalContainerEntityManagerFactoryBean bookEntityManager() {
 LocalContainerEntityManagerFactoryBean em
 = new LocalContainerEntityManagerFactoryBean();
 em.setDataSource(bookDataSource());
 em.setPackagesToScan(
 new String&#91;] { "com.dineshonjava.myapp.model.books"});

 HibernateJpaVendorAdapter vendorAdapter = new HibernateJpaVendorAdapter();
 em.setJpaVendorAdapter(vendorAdapter);
 Map<;String, Object> properties = new HashMap<;>();
 properties.put("hibernate.hbm2ddl.auto",
 env.getProperty("hibernate.hbm2ddl.auto"));
 properties.put("hibernate.dialect",
 env.getProperty("hibernate.dialect"));
 em.setJpaPropertyMap(properties);

 return em;
 }
 @Bean
 @Primary
 public PlatformTransactionManager bookTransactionManager() {

 JpaTransactionManager transactionManager
 = new JpaTransactionManager();
 transactionManager.setEntityManagerFactory(
 entityManager().getObject());
 return transactionManager;
 }
}</code></pre>



<p class="wp-block-paragraph">Next, let&#8217;s create Spring Boot autoconfiguration for the author database.</p>



<pre class="wp-block-code"><code>@Configuration
@EnableJpaRepositories(
 basePackages = "com.dineshonjava.myapp.dao.author", 
 entityManagerFactoryRef = "authorEntityManager", 
 transactionManagerRef = "authorTransactionManager")
public class PersistenceAuthorAutoConfiguration {
 
 @Bean
 @ConfigurationProperties(prefix="spring.author-datasource")
 public DataSource authorDataSource() {
 return DataSourceBuilder.create().build();
 }
 
 @Bean
 public LocalContainerEntityManagerFactoryBean authorEntityManager() {
 LocalContainerEntityManagerFactoryBean em
 = new LocalContainerEntityManagerFactoryBean();
 em.setDataSource(bookDataSource());
 em.setPackagesToScan(
 new String&#91;] { "com.dineshonjava.myapp.model.authors"});

 HibernateJpaVendorAdapter vendorAdapter = new HibernateJpaVendorAdapter();
 em.setJpaVendorAdapter(vendorAdapter);
 Map<;String, Object> properties = new HashMap<;>();
 properties.put("hibernate.hbm2ddl.auto",
 env.getProperty("hibernate.hbm2ddl.auto"));
 properties.put("hibernate.dialect",
 env.getProperty("hibernate.dialect"));
 em.setJpaPropertyMap(properties);

 return em;
 }

 @Bean
 public PlatformTransactionManager authorTransactionManager() {

 JpaTransactionManager transactionManager
 = new JpaTransactionManager();
 transactionManager.setEntityManagerFactory(
 entityManager().getObject());
 return transactionManager;
 }
}</code></pre>



<p class="wp-block-paragraph">Now we have defined the data source properties inside the <strong>application.properties</strong> according to the Boot autoconfiguration convention.</p>



<p class="wp-block-paragraph">You can see the above configuration files. These are annotating the data source bean creation method with @ConfigurationProperties and we have used the corresponding config prefix.</p>



<p class="wp-block-paragraph"><strong>DataSourceBuilder</strong> of Spring Boot takes care automatically how to create DataSource for each database using defined configurations.</p>



<h2 class="wp-block-heading">Summary</h2>



<p class="wp-block-paragraph">We have looked at a practical overview of how we can configure multiple databases into a Spring Boot application.</p>
<div class="wp-post-navigation"> 
									 <div class="wp-post-navigation-pre"> 
									 <a href="https://dineshonjava.com/designing-applications-with-spring-boot-and-react-js/">Previous</a> 
									 </div> 
									 <div class="wp-post-navigation-next"> 
									 <a href="https://dineshonjava.com/scheduler-scheduled-annotation-in-spring-boot/">Next</a> 
									 </div> 
									</div>
<script type="text/javascript">
jQuery(document).ready(function($) {
 $.post('https://dineshonjava.com/wp-admin/admin-ajax.php', {action: 'mts_view_count', id: '4611'});
});
</script>
Strategy Design Patterns We can easily create a strategy design pattern using lambda. To implement…
Decorator Pattern A decorator pattern allows a user to add new functionality to an existing…
Delegating pattern In software engineering, the delegation pattern is an object-oriented design pattern that allows…
Technology has emerged a lot in the last decade, and now we have artificial intelligence;…
Managing a database is becoming increasingly complex now due to the vast amount of data…
Overview In this article, we will explore Spring Scheduler how we could use it by…