Intro:

For many applications, database can simply be considered as an implementation detail, meaning that instead of heavily relying on the database, the application is designed in a way where the underlying method of storing and retrieving data is easily interchangeable. Often times for such applications, the application developers are responsible for maintaining the database as well. Although, we do have ORM tools like JPA (hibernate), we usually utilize these tools for querying and modifying the data, that is not enough though, is it? Now, I know all application developers love to create the schema scripts or the static data scripts manually :D but if you are like me, I would love to have the schema scripts and the static data scripts generated by my code itself. What about database maintenance? We would like an easy way to maintain our databases across multiple environments as well.

Today, we’ll look at a sample approach using a very simple example as to how we could potentially utilize these tools to make the application developers life easy and create as well as maintain a database using a code first approach. If you’d like to know the gist of what we are doing, please directly head over to the **Final Thoughts **section. The code in this article can be found at this repository.

Basic Setup:

To get started, head over to Spring Initializr and create a project by adding the following dependencies.

Spring Web
Spring Data JPA
Flyway Migration
H2 Database

We’ll start of by using the in-memory database H2, you can always later on move to using some other database like PostgreSql. You can either create a maven or a gradle project, that’s up to you. I’ve created a gradle project and the dependencies are as follows:

implementation 'org.springframework.boot:spring-boot-starter-data-jpa'
implementation 'org.springframework.boot:spring-boot-starter-web'
implementation 'org.flywaydb:flyway-core'
runtimeOnly 'com.h2database:h2'

Now, as code convention calls, let’s create a sample /greeting end-point that returns “Hello World” as the response. It always helps to know that things are working fine before we dive deep into the implementations.

import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class GreetingController {

    @GetMapping("/greeting")
    public String greeting() {
        return "Hello World!";
    }

}

Also, disable flyway for now since we do not want to get confused with the logs and/or the table it creates. Add the following property to application.properties

spring.flyway.enabled=false

Now once we run our main DatabaseApplication.class we would see a few logs related to h2, hibernate etc in the console, this is spring boot’s magical auto configuration in effect which configures a bunch of defaults for us based on the jars available on the classpath. We’ll come back to these logs later on. For now, we should be able to see “Hello World!” once we visit the /greeting end-point.

Image of visiting the url http://localhost:8080/greeting in the browser which returns a Hello World! response.

Now, let’s tweak our implementation a little bit so that a random greeting is returned every time we visit /greeting end-point.

@GetMapping("/greeting")
public String greeting() {
    return getRandomGreeting();
}

private String getRandomGreeting() {
    List<String> greetings = new ArrayList<>();
    greetings.add("Hello!");
    greetings.add("Good morning.");
    greetings.add("Good afternoon.");
    greetings.add("Good evening.");
    greetings.add("It's nice to meet you.");
    greetings.add("It's a pleasure to meet you.");
    Random random = new Random();
    int randomListIndex = random.nextInt(greetings.size());
    return greetings.get(randomListIndex);
}

A random greeting getting returned whenever the user visits the /greeting end-point.

This completes our basic setup, a few dependencies and a single /greeting GET end-point that returns a random greeting every time we visit it.

#migration #flyway #spring-boot #jpa

Code first database design & development using JPA, Flway, Fastnate...
5.05 GEEK