LoginSignup
17
14

More than 3 years have passed since last update.

SpringBootやってみる~DBアクセス(mybatis)編~ データ取得①

Last updated at Posted at 2020-04-10

目的

自己学習向け・初心者向けメモ。
今回はmybatisでDBアクセスをしてデータを取得するサンプルプログラムを作成する。

概要

MySQLのインストール

MySQLをインストールします。

※インストール方法については下記リンク参照
DBOnline

データベースの作成

アプリケーションで作成するデータベースを作成する
A5:SQL MK-2を使用します。

※データベースの接続方法については割愛しますが下記リンクを参照
データベースへの接続方法

テーブルの作成

ただ表示するだけなのでシンプルなテーブルを作成します。

【userinfo(ユーザー情報)】

論理名 論理名 文字数 制約
id ID integer NOT NULL, PRIMARY KEY
name 名前 varchar 255
sex 性別 varchar 1
create table userinfo (id integer NOT NULL PRIMARY KEY,
                       name varchar(255),
                       sex char(1)); 

次はデータを作成します。

INSERT INTO userinfo VALUES (1,'来栖翔','男');
INSERT INTO userinfo VALUES (2,'小野寺梓','女'); 

作成できたようなので確認...

SELECT * FROM userinfo;

image.png

確認できた (๑˃̵ᴗ˂̵)و ヨシ!(名前は気にしないでね)

アプリケーションの実装

アプリケーションの作成をします。
次にライブラリを選定します。選択したのは以下のとおりです。

項番 ライブラリ
1 Spring Boot DevTools
2 Lombok
3 Spring Configuration Processor
4 MyBatis Framework
5 MySQL Driver
6 Thymeleaf
7 Spring Web

image.png
image.png

パッケージ・エクスプローラーにプロジェクトが表示された╭( ・ㅂ・)و ̑̑ グッ !
image.png

フォルダ構成

image.png

application.propertiesの作成

application.properties
#MySQLのドライバ設定
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
#接続用URL
spring.datasource.url=jdbc:mysql://localhost/userinfo?serverTimezone=JST
#ユーザ名
spring.datasource.username=user1
#パスワード
spring.datasource.password=p@ssword

クラスとインターフェースの作成

entity、mapper、controllerを作成します。
・entity:変数とその setter、getter だけを持つクラス
MyBatis が、このクラスのにテーブルのデータを格納してくれる
・mapper:インターフェースですが、具象クラスは MyBatis が XML の SQL 情報等を使用し、自動で作成してくれ
・controller:MyBatis が自動で生成したマッパーの具象クラスを Spring が DI してくれる

UserInfo.java
package org.app.dbapp.entity;

public class UserInfo {

    private String id;
    private String name;
    private String sex;

    public String getId() {
        return id;
    }

    public void setId(String id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getSex() {
        return sex;
    }

    public void setSex(String sex) {
        this.sex = sex;
    }
}
UserInfoMapper.java
package org.app.dbapp.mapper;

import java.util.List;

import org.apache.ibatis.annotations.Mapper;
import org.app.dbapp.entity.UserInfo;

@Mapper
public interface UserInfoMapper {
    List<UserInfo> selectAll();
}
DemoController.java
package org.app.dbapp.controller;

import java.util.List;

import org.app.dbapp.entity.UserInfo;
import org.app.dbapp.mapper.UserInfoMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

@Controller
public class IndexController {

    @Autowired
    UserInfoMapper userInfoMapper;

    @RequestMapping
    public String index(Model model) {
        List<UserInfo> list = userInfoMapper.selectAll();
        model.addAttribute("userInfo", list);
        return "index";
    }
}

XMLファイルの作成

resource 配下に作成したフォルダに SQL を記載した XML ファイルを作成します。

UserInfoMapper.xml
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
        PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="org.app.dbapp.mapper.UserInfoMapper">
    <select id="selectAll" resultType="org.app.dbapp.entity.UserInfo">
        SELECT * FROM userinfo;
    </select>
</mapper>

Tymeleaf の作成

あとは、resources/templates 配下に Tymeleaf の配置します。

index.html
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
    <table border="1">
        <tr>
            <th>ID</th>
            <th>名前</th>
            <th>性別</th>
        </tr>
        <tr th:each="info: ${userInfo}">
            <td th:text="${info.id}"></td>
            <td th:text="${info.name}"></td>
            <td th:text="${info.sex}"></td>
        </tr>
    </table>
</body>
</html>

実行

Spring Boot App で起動して http://localhost:8080 にアクセスするとこのような画面が表示されます。
image.png

次回

SpringBootやってみる~DBアクセス(mybatis)編~ データ取得②

17
14
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
17
14