Spring Bootでアプリケーション作成②

はじめに

前回の続きでSpring Frameworkを使用したアプリケーションを作成します。
今回作成したコードはすべて以下にあげているので、良かったら参考にしてください。

github.com

エンティティークラスの作成

  • テーブルの列がエンティティークラスのフィールドに対応付けられる

  • 主キーを表す@Idを付与する

  • クラス名、フィールド名、フィールドの型にデータベースのテーブル名、列名、列型を指定することで、自動的にマッピングされる

  • Lombokの@Getter、@Setterを使用するのでgetter, setterメソッドは記述する必要なし(Lombokコンパイル時に自動で生成してくれる)

package com.spring.data.jpa.example.repository.entity;

import java.io.Serializable;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.EnumType;
import javax.persistence.Enumerated;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import lombok.Getter;
import lombok.Setter;
import lombok.ToString;

@Entity
@Getter
@Setter
@ToString
public class Employee implements Serializable {
    private static final long serialVersionUID = 1L;

    /**
     * 性別の列挙
     */
    public static enum Sex {
        male, female
    }

    /** 社員番号 */
    @Id
    @GeneratedValue
    private Integer no;

    /** 名前 */
    @Column(length = 20, nullable = false)
    private String firstName;

    /** 苗字 */
    @Column(length = 20, nullable = false)
    private String lastName;

    /** 性別 */
    @Column(length = 10)
    @Enumerated(EnumType.STRING)
    private Sex sex;

    /** 生年月日 */
    private java.sql.Date birthday;

    /** メールアドレス */
    @Column(unique = true)
    private String mailAddress;
}

サービスクラスの作成

  • テーブルの情報をすべて取得する
  • @Transactionalを使用して、メソッドが呼び出されるとトランザクションが開始される
package com.spring.data.jpa.example.service;

import java.util.List;

import com.spring.data.jpa.example.repository.entity.Employee;

public interface EmployeeService {
    public List<Employee> getEmployeeList();
}
package com.spring.data.jpa.example.service;

import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;

import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.spring.data.jpa.example.repository.entity.Employee;

@Service
@Transactional(readOnly = true)
public class EmployeeServiceImpl implements EmployeeService {
    @PersistenceContext
    private EntityManager entityManager;

    @Override
    public List<Employee> getEmployeeList() {
        return entityManager.createQuery("SELECT e FROM Employee e",
                                        Employee.class).getResultList();
    }
}

コントローラークラスの作成

  • 取得したテーブルのデータをモデルに設定する *テーブルの情報を画面にわたす

  • @RequestMappingを使用して、メソッドにアクセスするためのURLを定義する

  • 「/employee/lis」にアクセスすると、「list」メソッドが呼び出される

package com.spring.data.jpa.example.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

import com.spring.data.jpa.example.service.EmployeeService;

@Controller
@RequestMapping("employee")
public class EmployeeController {
    @Autowired
    private EmployeeService employeeService;

    @RequestMapping("list")
    public String list(Model model) {
        model.addAttribute("employees", employeeService.getEmployeeList());

        return "employee/list";
    }
}

テンプレートの作成

  • コントローラークラスから受け取ったデータを画面に表示する
<html xmlns="http://www.w3.org/1999/xhtml"
        xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<style type="text/css">

table {
    border-collapse: collapse;
}
th, td {
    border: 1px darkgray solid;
}

</style>
</head>
<body>
<table>
    <thead>
        <tr>
            <th>No</th>
            <th>First Name</th>
            <th>Last Name</th>
            <th>Sex</th>
            <th>Birthday</th>
            <th>Mail Address</th>
        </tr>
    </thead>
    <tbody>
        <tr th:each="employee : *{employees}">
            <td th:text="${employee.no}"></td>
            <td th:text="${employee.firstName}"></td>
            <td th:text="${employee.lastName}"></td>
            <td th:text="${employee.sex}"></td>
            <td th:text="${employee.birthday}"></td>
            <td th:text="${employee.mailAddress}"></td>
        </tr>
    </tbody>
</table>
</body>
</html>

SQLの作成

*起動時にテーブルのcreate、insertをしてくれる

CREATE TABLE IF NOT EXISTS employee (
    no INTEGER PRIMARY KEY,
    birthday DATE,
    first_name VARCHAR(20) NOT NULL,
    last_name VARCHAR(20) NOT NULL,
    mail_address VARCHAR(30),
    sex VARCHAR(10)
);
INSERT INTO employee
        ( no, birthday, first_name, last_name, mail_address, sex )
    VALUES
        (1,'1980-01-31','太郎','山田','taro.yamada@mail.com','male');
INSERT INTO employee
        ( no, birthday, first_name, last_name, mail_address, sex )
    VALUES
        (2,'1985-02-10','一郎','鈴木','ichiro.suzuki@mail.com','male');
INSERT INTO employee
        ( no, birthday, first_name, last_name, mail_address, sex )
    VALUES
        (3,'1985-03-10','花子','石井','hanako.ishii@mail.com','female');

アプリケーションを起動する

Spring Bootアプリケーションを実行 ⇒ URL『http:localhost:8080/employee/list』を入力 f:id:xxyoko10:20201227013717p:plain

テーブルのデータが表示されました。

補足

  • テーブルの作成方法について 今回は起動時に「schema.sql」を読み込むことで、テーブルを作成しました。
    「schema.sql」を作成しなくても、テーブルを自動で作成する方法があります。
    「application.properties」の設定を一部変更します。
spring.jpa.hibernate.ddl-auto=none
spring.jpa.hibernate.ddl-auto=create

「spring.jpa.hibernate.ddl-auto」の値を「create」に変えるだけです。
こうすることで、「schema.sql」がなくてもテーブルを自動で作成してくれます。
ちなみに、「spring.jpa.hibernate.ddl-auto=create」の状態で「schema.sql」を作成した場合、 テーブルのcreate、insertが失敗しました。

まとめ

テーブルのデータを取得して、画面に表示するアプリケーションを作成できました。

参考

Spring Data JPAプログラミング入門

Spring Data JPAプログラミング入門