Spring Boot - How to load initial data on startup - onlinetutorialspoint

PROGRAMMINGJava ExamplesC Examples
Java Examples
C Examples
C Tutorials
aws
JAVAEXCEPTIONSCOLLECTIONSSWINGJDBC
EXCEPTIONS
COLLECTIONS
SWING
JDBC
JAVA 8
SPRING
SPRING BOOT
HIBERNATE
PYTHON
PHP
JQUERY
PROGRAMMINGJava ExamplesC Examples
Java Examples
C Examples
C Tutorials
aws
In Spring Boot, we can load the initial data into the database while startup the application. It is a powerful feature while we are working with different environments. This tutorial will see how to load initial data on startup.
I wrote an article on spring boot + h2 database integration some time back. I loaded my SQL script, including DDL and DML, into the H2 DB while starting the application; however, check this for a complete example.
As we know that we can easily create the database tables with Spring Boot JPA entities like below.
package com.onlinetutorialspoint.model;

import javax.persistence.*;

@Entity
@Table(name = "items")
public class Item {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private long id;
    @Column(name="item_name")
    private String itemName;
    @Column(name="item_category")
    private String category;

    public Item() {
    }

    public Item(String itemName, String category) {
        this.itemName = itemName;
        this.category = category;
    }
    public long getId() {
        return id;
    }

    public String getItemName() {
        return itemName;
    }

    public String getCategory() {
        return category;
    }
}

Using the above entity class, we can create a item table in any database, but ultimately it’s an empty table now; let’s populate some data init.
So coming to the loading of initial data while startup, we need to separate our DDL (create) and DML (inserts/updates) scripts in two different files that are schema.sql and data.sql respectively. That way Spring Boot can differentiate the scripts.
If you are working with multiple database vendors, for example, MySQL and PostgreSQL you can make these files like schema-mysql.sql or schema-postgresql.sqlsimilar for data.sql files.
Based on your database, you have to configure the below property in the .properties file.
spring.datasource.platform=mysql   #specify vendor name here

Spring Boot always looks these files into the classpath resources – Hence we have to create these files in the src/main/resources folder so that these will be available automatically by the Spring context on startup.
schema.sql
CREATE TABLE `item` (
  `id` INT(11) NOT NULL,
  `name` VARCHAR(50) NULL DEFAULT NULL,
  `category` VARCHAR(50) NULL DEFAULT NULL,
  PRIMARY KEY (`id`)
);
data.sql
INSERT INTO `item` (`id`, `name`, `category`) VALUES (1, 'IPhone 6S', 'Mobile');
INSERT INTO `item` (`id`, `name`, `category`) VALUES (2, 'Samsung Galaxy', 'Mobile');
INSERT INTO `item` (`id`, `name`, `category`) VALUES (3, 'Lenovo', 'Laptop');
INSERT INTO `item` (`id`, `name`, `category`) VALUES (4, 'LG', 'Telivision');
I am not sure whether you noticed this or not? Do we really need schema.sqlfile? Because JPA entities create database tables while startup, right? So does it make any sense to you?
For me, it doesn’t make any sense, but still, there are some scenarios that we have to create tables from the startup scripts while having the entities in the source; in such cases, we have to tell the spring to remove the ambiguity by defining the below property in application.properties file.
spring.jpa.hibernate.ddl-auto=none
If you are using Spring Boot 2or later versions, this database initialization works only for in-memory databases like H2 and HSQLDB etc. So if we want to make this for other DBS we need to configure the spring.datasource.initialization-mode property in the .properties file below.
spring.datasource.initialization-mode=always
Done!
Spring Boot in-memory DB example
Spring Boot database auto initialization
Happy Learning 🙂

Spring Boot H2 Database + JDBC Template Example
Spring Boot MongoDB + Spring Data Example
Spring Boot Redis Data Example CRUD Operations
Spring Boot Lazy Loading Beans Example
Spring Boot Multiple Data Sources Example
Spring Boot JNDI Configuration – External Tomcat
Spring Boot PostgreSQL DB CRUD Example
Spring Boot MockMvc JUnit Test Example
Spring Boot JdbcTemplate CRUD Operations Mysql
Spring Boot Hazelcast Cache Example
Spring Boot DataRest Example RepositoryRestResource
Spring Boot EhCache Example
How to set Spring Boot SetTimeZone
Spring Boot In Memory Basic Authentication Security
Spring Boot Actuator Database Health Check

Spring Boot H2 Database + JDBC Template Example
Spring Boot MongoDB + Spring Data Example
Spring Boot Redis Data Example CRUD Operations
Spring Boot Lazy Loading Beans Example
Spring Boot Multiple Data Sources Example
Spring Boot JNDI Configuration – External Tomcat
Spring Boot PostgreSQL DB CRUD Example
Spring Boot MockMvc JUnit Test Example
Spring Boot JdbcTemplate CRUD Operations Mysql
Spring Boot Hazelcast Cache Example
Spring Boot DataRest Example RepositoryRestResource
Spring Boot EhCache Example
How to set Spring Boot SetTimeZone
Spring Boot In Memory Basic Authentication Security
Spring Boot Actuator Database Health Check
 


Δ
 Spring Boot – Hello World
 Spring Boot – MVC Example
 Spring Boot- Change Context Path
 Spring Boot – Change Tomcat Port Number
 Spring Boot – Change Tomcat to Jetty Server
 Spring Boot – Tomcat session timeout
 Spring Boot – Enable Random Port
 Spring Boot – Properties File
 Spring Boot – Beans Lazy Loading
 Spring Boot – Set Favicon image
 Spring Boot – Set Custom Banner
 Spring Boot – Set Application TimeZone
 Spring Boot – Send Mail
 Spring Boot – FileUpload Ajax
 Spring Boot – Actuator
 Spring Boot – Actuator Database Health Check
 Spring Boot – Swagger
 Spring Boot – Enable CORS
 Spring Boot – External Apache ActiveMQ Setup
 Spring Boot – Inmemory Apache ActiveMq
 Spring Boot – Scheduler Job
 Spring Boot – Exception Handling
 Spring Boot – Hibernate CRUD
 Spring Boot – JPA Integration CRUD
 Spring Boot – JPA DataRest CRUD
 Spring Boot – JdbcTemplate CRUD
 Spring Boot – Multiple Data Sources Config
 Spring Boot – JNDI Configuration
 Spring Boot – H2 Database CRUD
 Spring Boot – MongoDB CRUD
 Spring Boot – Redis Data CRUD
 Spring Boot – MVC Login Form Validation
 Spring Boot – Custom Error Pages
 Spring Boot – iText PDF
 Spring Boot – Enable SSL (HTTPs)
 Spring Boot – Basic Authentication
 Spring Boot – In Memory Basic Authentication
 Spring Boot – Security MySQL Database Integration
 Spring Boot – Redis Cache – Redis Server
 Spring Boot – Hazelcast Cache
 Spring Boot – EhCache
 Spring Boot – Kafka Producer
 Spring Boot – Kafka Consumer
 Spring Boot – Kafka JSON Message to Kafka Topic
 Spring Boot – RabbitMQ Publisher
 Spring Boot – RabbitMQ Consumer
 Spring Boot – SOAP Consumer
 Spring Boot – Soap WebServices
 Spring Boot – Batch Csv to Database
 Spring Boot – Eureka Server
 Spring Boot – MockMvc JUnit
 Spring Boot – Docker Deployment