今回の記事はSpringBootプロジェクトでMybatisを使ってDB接続とデータ表示を行う方法に関する記事です。ディレクトリ構成やコメントも詳細に記載しております。SpringBootとMybatis入門者で困っている方は是非記事参考にしてみてください。
SpringBootプロジェクト構成作成
ディレクトリ構成
ディレクトリ構成は下記のようになっています。まずはクラスを追加して下記構成を作成するところまで行いましょう。とこに触っていないフォルダは省略しています。
.
├── build.gradle
└── src
├── main
│ ├── java
│ │ └── org
│ │ └── example
│ │ ├── Main.java
│ │ ├── controller
│ │ │ └── UserController.java
│ │ ├── dto
│ │ │ └── UserSearchRequest.java
│ │ ├── entity
│ │ │ └── User.java
│ │ ├── repository
│ │ │ └── UserMapper.java
│ │ └── service
│ │ └── UserService.java
│ └── resources
│ ├── application.properties
│ └── templates
│ └── index.html
プロジェクトの始め方やクラスの追加方法は下記リンクよりSpringBootプロジェクトの始め方を紹介しているので、そちらを参照ください。
「SpringBootプロジェクトの始め方。〜 HelloWorld 〜」
ライブラリのインストール
次にgradleの設定を行います。gradleでライブラリを管理していますが、gradle以外でも問題ないので下記ライブラリを追加してください。
dependencies {
//testImplementation 'org.junit.jupiter:junit-jupiter-api:5.8.1'
//testRuntimeOnly 'org.junit.jupiter:junit-jupiter-engine:5.8.1'
implementation 'org.springframework.boot:spring-boot-starter-thymeleaf'
implementation 'org.springframework.boot:spring-boot-starter-web'
implementation 'org.mybatis.spring.boot:mybatis-spring-boot-starter:2.1.3'
//compileOnly 'org.projectlombok:lombok'
implementation 'org.springframework.boot:spring-boot-devtools'
runtimeOnly 'mysql:mysql-connector-java'
compileOnly 'org.projectlombok:lombok:1.18.8'
annotationProcessor 'org.projectlombok:lombok:1.18.8'
implementation 'org.springframework.boot:spring-boot-starter-tomcat'
testImplementation('org.springframework.boot:spring-boot-starter-test') {
exclude group: 'org.junit.vintage', module: 'junit-vintage-engine'
}
}
ではファイル内に記述を行なっていきます。
SpringBootプロジェクトでDB接続
DBは下記コマンドで作成します。
create table user (id int, name varchar(10));
DB接続に必要なファイルで下記を記述します。
spring.datasource.url=jdbc:mysql://localhost:3306/[データベース名]?serverTimezone=JST
spring.datasource.username=root
spring.datasource.password=[パスワード]
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
SpringBootでMybatisを使ってデータ取得と表示
Controller作成
package org.example.controller;
import org.example.dto.UserSearchRequest;
import org.example.entity.User;
import org.example.service.UserService;
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.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
// コントローラー
@Controller
public class UserController {
// サービス
@Autowired
UserService userService;
// ルーティング
@GetMapping(value = "/user/search")
public String displaySearch(Model model) {
model.addAttribute("userSearchRequest", new UserSearchRequest());
User[] user = userService.searchAll();
model.addAttribute("initData", user);
return "index";
}
@RequestMapping(value = "/user/id_search", method = RequestMethod.POST)
public String search(@ModelAttribute UserSearchRequest userSearchRequest, Model model) {
User user = userService.searchById(userSearchRequest);
model.addAttribute("userinfo", user);
return "index";
}
}
ブラウザでのget通信とボタンを押して検索を行う2通りのルーティングを用意しました。
Dto作成
package org.example.dto;
import lombok.Data;
import java.io.Serializable;
// フォーム
@Data
public class UserSearchRequest implements Serializable {
private Long id;
}
こちらのDtoは検索条件用のフォームの要素を格納するDtoです。id検索を行うので、idを定義しています。
Entity作成
package org.example.entity;
import lombok.Data;
// データの箱
@Data
public class User {
/**
* ID
*/
private Long id;
/**
* 名前
*/
private String name;
}
Entityデータベースのテーブル情報と同じにします。
Mapper作成
package org.example.repository;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Select;
import org.example.dto.UserSearchRequest;
import org.example.entity.User;
@Mapper
public interface UserMapper {
// 全件検索
@Select("select * from user")
User[] searchAll();
// ID検索
@Select("select * from user where id = #{id}")
User searchById(UserSearchRequest user);
}
MapperではSQLを定義します。全件検索とID検索の二つを用意しています。
こちらは「@Select」でSQLを記述していますが、XMLから取得する方法もあります。どちらか好きな方でやってください。
Service作成
package org.example.service;
import org.apache.ibatis.annotations.Select;
import org.example.dto.UserSearchRequest;
import org.example.entity.User;
import org.example.repository.UserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
@Service
public class UserService {
/**
* ユーザー情報 Mapper
*/
@Autowired
private UserMapper userMapper;
/**
* ユーザー情報検索
* @param userSearchRequest リクエストデータ
* @return 検索結果
*/
public User searchById(UserSearchRequest userSearchRequest) {
return userMapper.searchById(userSearchRequest);
}
public User[] searchAll() {
return userMapper.searchAll();
}
}
Serviceクラスでは先ほどの検索SQLを発行する部分となります。
HTML作成
では最後にHTMLです。初期表示時にはフォーム情報がからであり、かつ初期表示で登録されているデータ全件を表示するようにしています。
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:th="http://www.thymeleaf.org">
<head>
<title>ユーザー情報検索</title>
<meta charset="utf-8" />
</head>
<body>
<h1>ユーザー情報検索</h1>
<form th:action="@{/user/id_search}" th:object="${userSearchRequest}"
th:method="post">
<div>
ID:<input type="text" th:field="*{id}" />
</div>
<br />
<div>
<input type="submit" value="検索" />
</div>
<br />
</form>
<div th:if="${userinfo}">
<table th:object="${userinfo}">
<tr>
<th class="cell_title">名前</th>
<td th:text="*{name}"></td>
</tr>
</table>
</div>
<div th:if="${initData}">
<th:block th:each="color1 : ${initData}">
<p>
<!-- <span th:text="${color1.key}"></span>-->
<span th:text="${color1.name}"></span>
</p>
</th:block>
</div>
</body>
</html>
検索ボタンを押すとフォーム情報の中のIDでデータベースを検索するSQLを発行して、帰ってきたデータを表示するようになっています。
ではこちらをビルドして指定のURLにアクセスしてみましょう。
「http://localhost:8080/user/search」
以上で今回の記事は終了です。他にも多数のSpringBoot関連の記事を記載しているので是非参考にしてください。
コメント