Over a million developers have joined DZone.
{{announcement.body}}
{{announcement.title}}

Spring Boot and Database Initialization

DZone's Guide to

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

· Java Zone
Free Resource

Check out this 8-step guide to see how you can increase your productivity by skipping slow application redeploys and by implementing application profiling, as you code! Brought to you in partnership with ZeroTurnaround.

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

The Java Zone is brought to you in partnership with ZeroTurnaround. Check out this 8-step guide to see how you can increase your productivity by skipping slow application redeploys and by implementing application profiling, as you code!

Topics:
spring ,spring boot ,database

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

Opinions expressed by DZone contributors are their own.

The best of DZone straight to your inbox.

SEE AN EXAMPLE
Please provide a valid email address.

Thanks for subscribing!

Awesome! Check your inbox to verify your email so you can start receiving the latest in tech news and resources.
Subscribe

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}