Spring Boot/第三回 Spring Bootでデータベース操作(JDBC編)
Spring Bootでデータベース操作をする。
前回の準備編に続いて、今回はデータベースに対してデータの操作を行う。
Spring Bootでのデータベース操作は
の2種類があるが、今回はJDBCの方の話。
依存関係の追加
まずはMavenの依存関係を追加するが、前回の準備編と同じなので、すでに記述していたら不要。
<dependencies> <!-- append start --> <dependency> <!-- a --> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-jdbc</artifactId> </dependency> <dependency> <!-- b --> <groupId>com.h2database</groupId> <artifactId>h2</artifactId> </dependency> <dependency> <!-- c --> <groupId>org.projectlombok</groupId> <artifactId>lombok</artifactId> <version>1.14.0</version> <scope>provided</scope> </dependency> <!-- append end --> </dependencies>
a -> Spring BootでJDBCを扱うための依存関係。
b -> H2の依存関係。
c -> Lombokの依存関係。
行挿入
データベース操作はリポジトリの役目なので、CustomerRepositoryクラスに処理を書いて行く。
まずは行挿入から。
(第二回で宣言したgetCustomer()メソッドは不要なので削除した)
package tools.springsample.springsample03.repository; import tools.springsample.springsample03.domain.Customer; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate; import org.springframework.jdbc.core.namedparam.SqlParameterSource; import org.springframework.jdbc.core.namedparam.BeanPropertySqlParameterSource; import org.springframework.stereotype.Repository; @Repository public class CustomerRepository { @Autowired private NamedParameterJdbcTemplate jdbcTemplate; public Customer save(Customer customer) { // a SqlParameterSource param // b = new BeanPropertySqlParameterSource(customer); // c jdbcTemplate.update("insert into customer(name, email) " + " values(:name, :email)", param); // d return customer; } }
a -> 行挿入メソッド。これを実装する。
b -> SqlParameterSourceクラスは後のSQLの「:」で始まるプレースホルダのパラメータを保持するクラス。
c -> プレースホルダのマッピングにCustomerクラスのインスタンスを使用する。
Customerクラスのgetterメソッドを検知してデータを取得し、プレースホルダに当てはめてくれる。
d -> NamedParameterJdbcTemplateを使ってSQLを実行する。
第一引数がプレースホルダ付のSQL、第二引数がプレースホルダに当てはめる値が入ったcで作ったインスタンス。
プレースホルダの「:name」にCustomerクラスのgetName()メソッドで取得した値を、「:email」にgetEmail()メソッドで取得した値を当てはめてSQLを実行する。
続いてこのリポジトリクラスを呼び出すクラスを作成する。
package tools.springsample.springsample03; import tools.springsample.springsample03.domain.Customer; import tools.springsample.springsample03.repository.CustomerRepository; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.CommandLineRunner; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.EnableAutoConfiguration; import org.springframework.context.annotation.ComponentScan; @EnableAutoConfiguration @ComponentScan public class App implements CommandLineRunner { @Autowired private CustomerRepository customerRepository; @Override public void run(String... strings) throws Exception { Customer customer01 = new Customer(); // a customer01.setName("user01"); // b customer01.setEmail("user01@foo.bar"); // c customerRepository.save(customer01); // d } public static void main(String[] args) { SpringApplication.run(App.class, args); } }
a -> ドメインクラスCustomerのインスタンスを作成。
b -> Customerの初期化。フィールドnameに「user01」を設定する。
c -> Customerの初期化。フィールドemailに「user01@foo.bar」を設定する。
d -> リポジトリクラスの行挿入メソッドを呼び出す。
実行すると以下のようなSQLが実行される。
insert into customer(name, email) values('user01', 'user01@foo.bar')
コンパイルして実行
以下のようにコンパイルする。
今回は実行したいのでコンパイルしてJARファイルでパッケージする。
mvn package
続いて起動。
今回はコマンドライン実行する「CommandLineRunner」を拡張したAppクラスなので、下記のコマンドで実行。
JARファイルは適宜読み替えましょう。
java -jar target\SpringSample03-1.0-SNAPSHOT.jar
実行したあとデータベースを見ると下記のように登録される。
ID | NAME | |
---|---|---|
1 | user01 | user01@foo.bar |
業務でJDBCを使って実装することはまれだと思うので、JDBC編はここまで。
■ 参考文献 ■
この記事で参考にしたのは「はじめての Spring Boot」です。
はじめてのSpring Boot―「Spring Framework」で簡単Javaアプリ開発 (I・O BOOKS)
- 作者: 槇俊明
- 出版社/メーカー: 工学社
- 発売日: 2014/11
- メディア: 単行本
- この商品を含むブログ (4件) を見る