Spring Boot | Database Access | Hello World

Database Access

  • Add spring-boot-starter-jdbc and the database dependency, such as org.hsqldb:hsqldb.
  • The configured database can then run in memory.
  • Because data is stored in memory, it is lost when the JVM stops.
  • H2 and Derby can also be used as embedded databases.

Writing the Code

build.gradle

dependencies {
    compile 'org.hsqldb:hsqldb'
    compile 'org.springframework.boot:spring-boot-starter-jdbc'
}

src/main/java/sample/springboot/Main.java

package sample.springboot;

import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.jdbc.core.JdbcTemplate;

@SpringBootApplication
public class Main {

    public static void main(String[] args) {
        try (ConfigurableApplicationContext ctx = SpringApplication.run(Main.class, args)) {
            Main m = ctx.getBean(Main.class);
            m.method();
        }
    }

    @Autowired
    private JdbcTemplate jdbc;

    public void method() {
        this.jdbc.execute("CREATE TABLE TEST_TABLE (ID INTEGER NOT NULL IDENTITY, VALUE VARCHAR(256))");

        this.jdbc.update("INSERT INTO TEST_TABLE (VALUE) VALUES (?)", "hoge");
        this.jdbc.update("INSERT INTO TEST_TABLE (VALUE) VALUES (?)", "fuga");
        this.jdbc.update("INSERT INTO TEST_TABLE (VALUE) VALUES (?)", "piyo");

        List<Map<String, Object>> list = this.jdbc.queryForList("SELECT * FROM TEST_TABLE");
        list.forEach(System.out::println);
    }
}

Result

{ID=0, VALUE=hoge}
{ID=1, VALUE=fuga}
{ID=2, VALUE=piyo}

Storing Data in a File

  • Define spring.datasource.url in the properties file to specify a JDBC connection URL.
  • For HSQLDB, the URL determines whether data is stored in a file. The following setting enables file storage.

application.properties

spring.datasource.url=jdbc:hsqldb:file:./db/testdb;shutdown=true