SpringBootでグループウェアの開発③〜DB接続の続き〜


DB接続の続き

前回でDB接続をして、新規登録まで作ろうとしたのですが、そこまでいかなかったので続きをやっていきます!

とりあえずここまでビルド&実行できるか確認

build.gradleを編集した際に自動でクラスパスの読み込みをするかのダイアログが右下に出てきたので、自動で読み込む設定にしました。
虫マークのデバッグメニューを開くと、初めてのデバッグの場合はlaunch.jsonを作るボタンがあるので、launch.jsonを作成する。
デバッグメニューでDemoAppcationから始められるので、デバッグをスタートします!


とりあえず実行は出来た。

MyBatisでマッピング

jpaとかの選択肢もあるけど、SQLを書く現場の方が多そうだからMyBatisでマッピングすることにした。

build.gradle

build.gradleのdependencies内に以下を追加。mybatisはバージョン指定しないと読み込んでくれないので、mvnrepositoryで希望するバージョンを調べて指定する。今回は2.1.1。

implementation 'org.mybatis.spring.boot:mybatis-spring-boot-starter:2.1.1'

マッパー作成

UserMapper.java
package パッケージ名.プロジェクト名.domain.repository;

import java.util.List;

import org.apache.ibatis.annotations.Delete;
import org.apache.ibatis.annotations.Insert;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Select;
import org.apache.ibatis.annotations.Update;

import rsrepo.groupware.mygroupware.domain.model.User;

@Mapper
public interface UserMapper {
    // 登録用メソッド
    @Insert("INSERT INTO users ( name, password, role ) VALUES ( #{name}, #{password}, #{role} )")
    public boolean insert(User user);

    // 1件検索用メソッド
    @Select("SELECT id, name, password, role, updated_at FROM users WHERE name = #{name} AND password = #{password}")
    public User selectOne(String userId);

    // 全件検索用メソッド
    @Select("SELECT id, name, password, role, updated_at FROM users")
    public List<User> selectMany();

    // 1件更新用メソッド
    @Update("UPDATE users SET name = #{name}, password = #{password}, role = #{role} WHERE id = #{id}")
    public boolean updateOne(User user);

    // 1件削除用メソッド
    @Delete("DELETE FROM users WHERE id = #{id}")
    public boolean deleteOne(String userId);
}

サービスの作成

UserService.java
package パッケージ名.プロジェクト名.domain.service;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import rsrepo.groupware.mygroupware.domain.model.User;
import rsrepo.groupware.mygroupware.domain.repository.UserMapper;

@Transactional
@Service
public class UserService {
    @Autowired
    UserMapper userMapper;

    // 登録用メソッド
    public boolean insert(User user) {
        return userMapper.insert(user);
    }

    // 1件検索用メソッド
    public User selectOne(String id) {
        return userMapper.selectOne(id);
    }

    // 全件検索用メソッド
    public List<User> selectMany() {
        return userMapper.selectMany();
    }

    // 1件更新用メソッド
    public boolean update(User user) {
        return userMapper.updateOne(user);
    }

    // 1件削除用メソッド
    public boolean delete(String id) {
        return userMapper.deleteOne(id);
    }
}

コントローラーを作成

UserController.java
package パッケージ名.プロジェクト名.controller;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import rsrepo.groupware.mygroupware.domain.model.User;
import rsrepo.groupware.mygroupware.domain.service.UserService;

@RestController
public class UserController {
    @Autowired
    UserService service;

    // ユーザー全件取得
    @GetMapping("/user/get")
    public List<User> getUserMany() {
        // ユーザー全件取得
        return service.selectMany();
    }

    // ユーザー1件取得
    @GetMapping("/user/get/{id}")
    public User getUserOne(@PathVariable("id") String userId) {
        // ユーザー1件取得
        return service.selectOne(userId);
    }

    // ユーザーを1件登録
    @PostMapping("/user/insert")
    public String putUserOne(@RequestBody User user) {
        boolean result = service.insert(user);
        String str = "";
        if (result) {
            str = "{\"result\":\"ok\"}";
        } else {
            str = "{\"result\":\"error\"}";
        }
        // 結果用の文字列をリターン
        return str;
    }

    // ユーザーを1件更新
    @PutMapping("/user/update")
    public String postUserOne(@RequestBody User user) {
        boolean result = service.update(user);
        String str = "";
        if (result) {
            str = "{\"result\":\"ok\"}";
        } else {
            str = "{\"result\":\"error\"}";
        }
        // 結果用の文字列をリターン
        return str;
    }

    // ユーザーを1件削除
    @DeleteMapping("/user/delete/{id:.+}")
    public String deleteUserOne(@PathVariable("id") String userId) {
        boolean result = service.delete(userId);
        String str = "";
        if (result) {
            str = "{\"result\":\"ok\"}";
        } else {
            str = "{\"result\":\"error\"}";
        }
        // 結果用の文字列をリターン
        return str;
    }
}

接続確認

DockerのMySQLを起動してテストデータを入れる。

INSERT INTO users ( name, password, role ) VALUES ( "test", "test", "ROLE_ADMIN" );

SpringBootを実行→http://localhost:8080/user/getにアクセス。

[{"id":"1","name":"test","password":"test","role":"ROLE_ADMIN","updated_at":"2020-01-22T12:17:56.000+0000"}]

jsonでデータが返される。

終わりに

やっとDB接続が完了したので、次回はログイン機能を完成させる事を目標に進めていこうと思います!
SpringBootでグループウェアの開発②〜DB接続〜
GitHub:MyGroupware