DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Please enter at least three characters to search
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Zones

Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks

Last call! Secure your stack and shape the future! Help dev teams across the globe navigate their software supply chain security challenges.

Modernize your data layer. Learn how to design cloud-native database architectures to meet the evolving demands of AI and GenAI workloads.

Releasing software shouldn't be stressful or risky. Learn how to leverage progressive delivery techniques to ensure safer deployments.

Avoid machine learning mistakes and boost model performance! Discover key ML patterns, anti-patterns, data strategies, and more.

Related

  • Actuator Enhancements: Spring Framework 6.2 and Spring Boot 3.4
  • How Spring Boot Starters Integrate With Your Project
  • A Practical Guide to Creating a Spring Modulith Project
  • Structured Logging in Spring Boot 3.4 for Improved Logs

Trending

  • How to Submit a Post to DZone
  • DZone's Article Submission Guidelines
  • How Large Tech Companies Architect Resilient Systems for Millions of Users
  • Medallion Architecture: Why You Need It and How To Implement It With ClickHouse
  1. DZone
  2. Coding
  3. Frameworks
  4. Spring Boot and Database Initialization

Spring Boot and Database Initialization

Spring Boot is packed with great features. Check out these code samples for how to perform DB initialisation in your projects

By 
Emmanouil Gkatziouras user avatar
Emmanouil Gkatziouras
DZone Core CORE ·
May. 12, 16 · Tutorial
Likes (9)
Comment
Save
Tweet
Share
143.5K Views

Join the DZone community and get the full member experience.

Join For Free

Spring Boot is hands down a great framework, saving the developer a lot of time and energy when developing a Spring application. One of its great features is database initialization. For example, you can use Spring Boot to initialize your sql database.

We will start with the gradle file:

group 'com.gkatzioura'
version '1.0-SNAPSHOT'

apply plugin: 'java'

sourceCompatibility = 1.5

buildscript {
 repositories {
 mavenCentral()
 }
 dependencies {
 classpath("org.springframework.boot:spring-boot-gradle-plugin:1.3.3.RELEASE")
 }
}

apply plugin: 'idea'
apply plugin: 'java'
apply plugin: 'spring-boot'

repositories {
 mavenCentral()
} 

dependencies {
 compile("org.springframework.boot:spring-boot-starter-web") {
 exclude module: "spring-boot-starter-tomcat"
 }
 compile("org.springframework.boot:spring-boot-starter-jetty")
 compile("org.springframework:spring-jdbc")
 compile("org.springframework.boot:spring-boot-starter-actuator")
 compile("com.h2database:h2:1.4.191")
 testCompile group: 'junit', name: 'junit', version: '4.11'
}

Pay special attention to the org.springframework:spring-jdbc dependency. Actually, this is the dependency that assists with the database initialization. The H2 database engine is more than enough for this example.

The application's main class:

package com.gkatzioura.bootdatabaseinitialization;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.ApplicationContext;

/**
 * Created by gkatzioura on 29/4/2016.
 */
@SpringBootApplication
public class Application {

 public static void main(String[] args) {

 SpringApplication springApplication = new SpringApplication();
 ApplicationContext applicationContext = springApplication.run(Application.class,args);
 }

}


The next step is to specify the datasource:

package com.gkatzioura.bootdatabaseinitialization.config;

import org.h2.jdbcx.JdbcDataSource;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;

import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.sql.DataSource;

/**
 * Created by gkatzioura on 29/4/2016.
 */
@Configuration
public class DataSourceConfig {

 private static final String TEMP_DIRECTORY = System.getProperty("java.io.tmpdir");

 @Bean(name = "mainDataSource")
 public DataSource createMainDataSource() {

 JdbcDataSource ds = new JdbcDataSource();
 ds.setURL("jdbc:h2:"+TEMP_DIRECTORY+"/testdata;MODE=MySQL");
 return ds;
 }

}

We will add a schema.sql file to the resource folder so it would be loaded to classpath. The schema.sql file will contain all the table definitions needed for our database.

CREATE TABLE IF NOT EXISTS `Users` (
 `user_id` bigint(20) NOT NULL AUTO_INCREMENT,
 `name` varchar(200) NOT NULL,
 PRIMARY KEY (`user_id`)
);

The next file to add is data.sql in the resources folder. This file will contain the sql statements needed to populate our database.

INSERT INTO `Users` (`user_id`,`name`) VALUES (null,'nick');
INSERT INTO `Users` (`user_id`,`name`) VALUES (null,'george');

On initialization spring boot will search for the data.sql and schema.sql files and execute them with the Database initializer.

So far so good; however, when you have two datasources defined, things get complicated.

Let's add a secondary datasource:

package com.gkatzioura.bootdatabaseinitialization.config;

import org.h2.jdbcx.JdbcDataSource;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;

import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.sql.DataSource;

/**
 * Created by gkatzioura on 29/4/2016.
 */
@Configuration
public class DataSourceConfig {

 private static final String TEMP_DIRECTORY = System.getProperty("java.io.tmpdir");

 @Bean(name = "mainDataSource")
 public DataSource createMainDataSource() {

 JdbcDataSource ds = new JdbcDataSource();
 ds.setURL("jdbc:h2:"+TEMP_DIRECTORY+"/testdata;MODE=MySQL");
 return ds;
 }

 @Bean(name = "secondaryDataSource")
 public DataSource createSecondaryDataSource() {

 JdbcDataSource ds = new JdbcDataSource();
 ds.setURL("jdbc:h2:"+TEMP_DIRECTORY+"/secondarydata;MODE=MySQL");
 return ds;
 }
}

When starting the application we get an error:

Caused by: org.springframework.beans.factory.NoUniqueBeanDefinitionException: No qualifying bean of type [javax.sql.DataSource] is defined: expected single matching bean but found 2: mainDataSource,secondaryDataSource

The problem is that the datasource initializer gets injected with a datasource. So we have to specify which datasource to inject, or else we will get an exception.

 A workaround is to specify which datasource bean is the primary one.

@Bean(name = "mainDataSource")
 @Primary
 public DataSource createMainDataSource() {

 JdbcDataSource ds = new JdbcDataSource();
 ds.setURL("jdbc:h2:"+TEMP_DIRECTORY+"/testdata;MODE=MySQL");
 return ds;
 }

By doing so the initializer will run the schema.sql and data.sql scripts using the mainDataSource bean.

Another great feature of Spring Boot database is initialization is that it can be integrated with flyway. Get more information on flyway here.

You can find the project source code here

Spring Framework Spring Boot Database engine

Published at DZone with permission of Emmanouil Gkatziouras, DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

Related

  • Actuator Enhancements: Spring Framework 6.2 and Spring Boot 3.4
  • How Spring Boot Starters Integrate With Your Project
  • A Practical Guide to Creating a Spring Modulith Project
  • Structured Logging in Spring Boot 3.4 for Improved Logs

Partner Resources

×

Comments
Oops! Something Went Wrong

The likes didn't load as expected. Please refresh the page and try again.

ABOUT US

  • About DZone
  • Support and feedback
  • Community research
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 100
  • Nashville, TN 37211
  • support@dzone.com

Let's be friends:

Likes
There are no likes...yet! 👀
Be the first to like this post!
It looks like you're not logged in.
Sign in to see who liked this post!