SpringBoot+MySQL: dbに接続し、レコードを追加・表示する
はじめに
こんにちは。
SpringBootでdb接続してブラウザからレコードを追加&レコードを取得してブラウザに表示する方法をメモります。
今回やりたいことは、ユーザ名とメールアドレスのセットをHTTPメソッドを介してdbへInsertし、登録されたデータ一覧をブラウザに表示すること。↓の環境を前提に進めていきます。
では行ってみましょー!
手順
SpringBootでdb接続、レコードの登録・取得、htmlへの表示を↓のようなステップで行っていきます。
1. 事前準備:プラグイン・設定ファイル等セットアップ
さっそく、Spring Starter Projectでプロジェクト作成していきましょう。DependenciesはWebのみを選択し、プロジェクト名はsample_dbとします。
この記事を通して出来上がるディレクトリは↓のような構成。
まずは、必要なプラグインの追加から。build.gradleを開いて、1, 2を追記します。なお、テンプレートエンジンにTymeleafを使いますので、記述のない方は追記してください。
dependencies {
//1 : jpa
compile 'org.springframework.boot:spring-boot-starter-data-jpa'
//2 : mysql connector
compile 'mysql:mysql-connector-java'
//3 : tymeleaf
compile('org.springframework.boot:spring-boot-starter-thymeleaf')
implementation 'org.springframework.boot:spring-boot-starter-web'
testImplementation 'org.springframework.boot:spring-boot-starter-test'
}
2. MySQL:ユーザ・db作成
sample_dbという名前でdbを作成します。また、ユーザ名をsampleuser、パスワードをpasswordとします。最後に、grant allでsample_dbに対する全ての権限をsampleuserに与えます。
mysql> create database sample_db;
Query OK, 1 row affected (0.01 sec)
mysql> create user 'sampleuser'@'%' identified by 'password';
Query OK, 0 rows affected (0.01 sec)
mysql> grant all on sample_db.* to 'sampleuser'@'%';
Query OK, 0 rows affected (0.00 sec)
続いて、resources/application.propertiesの編集。先ほど作成したdb、ユーザ、パスワード等をそれぞれ記述していきます。
spring.jpa.hibernate.ddl-auto=create
spring.datasource.url=jdbc:mysql://localhost:3306/sample_db
spring.datasource.username=sampleuser
spring.datasource.password=password
3. Java:Entityクラス作成
MySQLの準備ができたので、次はEntityクラスの作成です。
Entityクラスとは、dbで扱うデータをアプリケーションで保持するための入れ物のようなものです。なので、データの受け渡しはEntityクラスを介して行うことになります。今回は、クラス名をUserとします。
package com.example.demo;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
@Entity
public class User {
@Id
@GeneratedValue(strategy=GenerationType.AUTO)
private Integer id;
private String name;
private String email;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
}
@Entity: このクラスがEntityクラスであることを示します。
@Idは: これが付与されたフィールドはプライマリキーとして扱われる。
@GeneratedValue(strategy=GenerationType.AUTO): ユニークなキーを自動で生成してくれます。
4. Java:リポジトリ作成
リポジトリとは、Entityクラスで保持されるデータをCRUDしてくれるクラスです。UserRepositoryという名前で作成しましょう。
package com.example.demo;
import org.springframework.data.repository.CrudRepository;
public interface UserRepository extends CrudRepository{
}
5. Java:コントローラ作成
続いて、コントローラの作成。
/add+パラメータでアクセスされた時に、そのパラメータをdbにinsertし、/allでアクセスされた時に、user.htmlを返しそこにdbからselectしたuser一覧を表示するようにします。
package com.example.demo;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
@Controller
public class MainController {
@Autowired
private UserRepository userRepository;
@GetMapping("/add")
public @ResponseBody String addNewUser (@RequestParam String name
, @RequestParam String email) {
User n = new User();
n.setName(name);
n.setEmail(email);
userRepository.save(n);
return "saved";
}
@GetMapping("/all")
public String getAllUsers(Model model) {
List users = (List) userRepository.findAll();
model.addAttribute("users", users);
return "user";
}
}
@Controller: こいつをつけることで、そのクラスはコントローラをして扱われる。
@Autowired: プログラム中でクラスをnewすることなくインスタンス化してくれる。
@GetMapping: GETリクエストのみをマッピング。
6. HTML:データの表示
Tymeleafのタグを使って、取得したデータを表示します。
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
<table>
<tr>
<td>User</td>
<td>E-mail</td>
</tr>
<tr th:each="user: ${users}">
<td th:text="${user.name}"></td>
<td th:text="${user.email}"></td>
</tr>
</table>
</body>
</html>
以上で完成です。さっそく試してみましょう。ブラウザを開いて、アドレスバーで以下のURLを叩いてみましょう。
Savedと返って来れば成功です。
続いて、レコードを取得。/allにアクセスしてみましょう。
先ほど登録したtomさんが入ってますね。
これで以上になります。お疲れ様でした。
ではまた〜。
参考