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
Refcards Trend Reports Events Over 2 million developers have joined DZone. Join Today! Thanks for visiting DZone today,
Edit Profile Manage Email Subscriptions Moderation Admin Console How to Post to DZone Article Submission Guidelines
View Profile
Sign Out
Refcards
Trend Reports
Events
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
  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

Emmanouil Gkatziouras user avatar by
Emmanouil Gkatziouras
CORE ·
May. 12, 16 · Tutorial
Like (9)
Save
Tweet
Share
142.54K 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.

Popular on DZone

  • 13 Code Quality Metrics That You Must Track
  • Too Many Tools? Streamline Your Stack With AIOps
  • API Design Patterns Review
  • Spring Cloud: How To Deal With Microservice Configuration (Part 1)

Comments

Partner Resources

X

ABOUT US

  • About DZone
  • Send feedback
  • Careers
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

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

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 600 Park Offices Drive
  • Suite 300
  • Durham, NC 27709
  • support@dzone.com
  • +1 (919) 678-0300

Let's be friends: