プログラマーの調べ物

プログラマーが調べ物をするときに役に立つサイトを作ります。

Spring Bootでデータベースにアクセスしてみる。

Spring BootではSpring JDBCが簡単に使えます。 DBアクセスが必要なアプリケーションも非常に簡単に作ることができます。 正直、拍子抜けするくらいに。

pom.xmlに以下を追記します。

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-jdbc</artifactId>
</dependency>
<dependency>
    <groupId>com.h2database</groupId>
    <artifactId>h2</artifactId>
    <scope>runtime</scope>
</dependency>

次に、DBのデータを突っ込むBeanクラスを作りましょう。

package com.example;

import java.io.Serializable;

public class Message implements Serializable {
    private String text;

    public String getText() {
        return text;
    }

    public void setText(String text) {
        this.text = text;
    }
    
}

そして、JDBCとの接続クラスを作ります。

package com.example;

import java.util.List;
import java.util.concurrent.CopyOnWriteArrayList;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("messages")
public class MessageController {
    
    @Autowired
    JdbcTemplate jdbcTemplate;
    
    final List<Message> messages = new CopyOnWriteArrayList<>();
    
    @RequestMapping(method = RequestMethod.GET)
    public List<Message> getMessages() {
        return jdbcTemplate.query("SELECT text FROM messages ORDER BY id", (rs, i) -> {
            Message m = new Message();
            m.setText(rs.getString("text"));
            return m;
        });
    }
    
    @RequestMapping(method = RequestMethod.POST)
    public Message postMessages(@RequestBody Message message) {
        jdbcTemplate.update("INSERT INTO messages(text) VALUES (?)",message.getText());
        return message;
    }
    
}

これでソースの準備は完了です。

Spring Bootはデフォルトの挙動として、クラスパス直下にschema.sqlが存在すると、起動時にSQOファイルを実行します。 /src/main/resources以下にdbというソースフォルダを作りましょう。

普通のフォルダではなく、ソースフォルダを作ります。 そのdbソースフォルダの下に、schema.sqlファイルを作成します。

schema.sql

CREATE TABLE messages (
    id INT PRIMARY KEY AUTO_INCREMENT,
    text VARCHAR(255)
);

同じdbフォルダに、data.sqlを作ります。
http://docs.spring.io/spring-boot/docs/current/reference/html/howto-database-initialization.html

公式ドキュメントによると、起動時にdata.sqlに定義されているデータを挿入してくれます。

data.sql

INSERT INTO MESSAGES (text) VALUES('sample');

これでJavaを実行します。

http://localhost:8080/messages

にリクエストを飛ばすと、

json [{"text":"sample"}]

というJSONが返ってきます。