Spring Data JPA、データの取得や保存


Spring DataJPAとは

Javaの標準仕様であるJPAでDBアクセスができるライブラリ

テーブルを自動作成する

1.SpringDataJPAでテーブルを作成
2.H2コンソールのアクセス

依存関係

 ・SpringBootDevTools
 ・Lombok
 ・Spring DataJPA
 ・H2 Database
 ・Spring WEB

モデルの作成

 
 @Entity
  データの入れ物である「エンティティ(クラス)」であることを指定
 @id
  エンティティの主キーを設定
 @GeneratedValue
  主キーの値を自動採番

package com.example.demo;

import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import lombok.Getter;
import lombok.Setter;

@Getter
@Setter
@Entity
public class Book {
    @Id
    @GeneratedValue
    private Long id;
    private String title;
    private String detail;
}

H2 Databaseの設定

 application.propertiesを編集

spring.datasource.generate-unique-name=false

確認

 1.接続を押すとDBに接続できる
 
 2.Bookを選択するとSQLステートメントに「select*FROMBOOK」が表示されて実行ボタンを押下する
 ※1件も登録していないのでレコードは「該当行無し」と表示される

データの取得や保存をする

 1.DBのデータを取得保存する
 2.Spring Boot起動時にデータをロードする

依存関係

 ・Spring BootDevTools
 ・Lombok
 ・検証
 ・Spring Data JPA
 ・H2 Database
 ・thymeleaf
 ・Spring Web

モデルの作成

 CommentRepository.javaを以下のように編集
 JpaRepositoryを継承(extends)するだけで、
 DBの取得や保存など便利な機能が使えるようになる

package com.example.demo.repository;

import org.springframework.data.jpa.repository.JpaRepository;
import com.example.demo.Comment;

public interface CommentRepository extends JpaRepository <Comment,Long>{
}

コントローラ作成

以下のように編集 

package com.example.demo.controller;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PostMapping;

import com.example.demo.Comment;
import com.example.demo.repository.CommentRepository;

@Controller
public class CommentController {

    private final CommentRepository repository;
    public CommentController(CommentRepository repository) {
        this.repository = repository;
    }

    @GetMapping("/")
    public String getAllComments(@ModelAttribute Comment comment,Model model) {
        model.addAttribute("comments",repository.findAll());
        return"list";
    }

    @PostMapping("/add")
    public String addComment(@Validated @ModelAttribute Comment comment,BindingResult result,Model model) {
        model.addAttribute("comments",repository.findAll());
        if(result.hasErrors()) {
            return"list";
        }
        repository.save(comment);
        return "redirect:/";
    }
}

データローダを作成

 @RequiredArgsConstructor
 コンストラクタを自動生成します。因数は、finalなフィールド
 lombokの「@RequiredArgsConstructor」を使うとコンストラクタインジェクションを省略できる

package com.example.demo.config;

import org.springframework.boot.CommandLineRunner;
import org.springframework.stereotype.Component;

import com.example.demo.Comment;
import com.example.demo.repository.CommentRepository;

import lombok.RequiredArgsConstructor;

@RequiredArgsConstructor
@Component
public class DataLoader implements CommandLineRunner{

    private final CommentRepository repository;
    @Override
    public void run(String...args) throws Exception{
        Comment comment = new Comment();
        comment.setConten("こんにちは");
        repository.save(comment);

        comment = new Comment();
        comment.setConten("テストコメント");
        repository.save(comment);
    }
}

thymeleafを作成

 

<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>一言コメント</title>
</head>
<body>
 <h3>一言コメント</h3>
 <form th:action="@{/add}" th:object="${comment}"method="post">
  <label for="content">コメント</label>
 <input type="text" th:field="*{content}">
 <button>登録</button>
 <br>
 <small style="color:red" th:errors="*{content}"></small>
 </form>
 <br>
 <h3>一覧</h3>
 <div th:each="comment:${comments}" th:inline="text">
 <div>[[${comment.id]]-[[${comment.content}]]</div>
 </div>
</body>
</html>

確認

登録ボタンを押下後一覧に表示されていることを確認。

また、登録されたデータが登録されていることを確認

以上