かずきのBlog@hatena

すきな言語は C# + XAML の組み合わせ。Azure Functions も好き。最近は Go 言語勉強中。日本マイクロソフトで働いていますが、ここに書いていることは個人的なメモなので会社の公式見解ではありません。

Spring Bootでデータベースを扱う

h2データベースでさくっと試してみました。

pom.xmlに以下の記述を追加。今回はh2なのでh2のjdbcドライバを追加してます。SQL ServerならSQL ServerのJDBCドライバを追加するといいと思います。

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

そして、JPAのリポジトリを有効にするためAppクラスにEnableJpaRepositoriesアノテーションを追加します。

package okazuki.todoboot;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;

@SpringBootApplication
@EnableJpaRepositories
public class App {
    public static void main(String[] args) {
        SpringApplication.run(App.class, args);
    }
}

あとはRepositoryインターフェースを定義しておしまい。

package okazuki.todoboot.repositories;

import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;

import okazuki.todoboot.entities.Person;

@Repository
public interface PeopleRepository extends JpaRepository<Person, Integer> {

}

このリポジトリに命名規約に従ったメソッドを生やすことで、任意のJPQLを発行する機能があったりします。

2. JPA Repositories

リポジトリを使うクラスではAutowiredでDIしてもらいます。

package okazuki.todoboot.controllers;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import okazuki.todoboot.repositories.PeopleRepository;

@Controller
@RequestMapping("/people")
public class PeopleController {
    
    @Autowired
    PeopleRepository peopleRepotiroty;
    
    @RequestMapping(method = RequestMethod.GET)
    public String get(Model model) {
        model.addAttribute("people", this.peopleRepotiroty.findAll());
        return "peopleList";
    }
}

これはお手軽だわ。