LoginSignup
14
20

More than 5 years have passed since last update.

Spring Boot + JPA + MySQLでREST APIを実装する

Last updated at Posted at 2017-05-06

表題に向けて実装します。今回はこれまで作成したThymeleafを呼ぶコントローラは残したまま、新しいREST APIコントローラを追加します。また、DBへの接続にjdbcを利用していましたが、ORマッパのSpring Data JPAを利用するように変更します。

共通部分の修正

追加・修正ファイル
1.png

usersテーブルの定義

com.example.User.java
package com.example;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;

@Entity
@Table(name = "users")
public class User {
    @Id
    @Column(name = "id")
    private int id;
    @Column(name = "name")
    private String name;

    public int getId() {
        return id;
    }
    public void setId(int id) {
        this.id = id;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
}

DBに接続するサービスクラス定義

com.example.Repository.UsersRepository.java
package com.example.Repository;

import java.util.List;
import org.springframework.data.jpa.repository.JpaRepository;
import com.example.User;

public interface UsersRepository extends JpaRepository<User, Integer> {
    public List<User> findById(int id);
}

DB接続の設定
driver-class-nameが古かったので修正

src/main/resources/application.properties
spring.datasource.url=jdbc:mysql://127.0.0.1:3306/DB名
spring.datasource.username=ユーザ名
spring.datasource.password=パスワード
spring.datasource.driver-class-name=com.mysql.jdbc.Driver

依存の設定
ORマッパを利用するため追加

pom.xml
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>

APIの仕様

DB
以下のようにusersテーブルを作成して、テーブルに対してRESTでデータを操作します。

CREATE TABLE user (
  id int AUTO_INCREMENT,
  name varchar(254),
  INDEX(id)
);

API一覧

NO METHOD url 動作
1 GET /users テーブル全件参照
2 GET /users/id id指定した1件参照
3 POST /users レコード登録
4 PUT /users/id 1レコード更新
5 DELETE /users/id 1レコード削除

1 GET /users

com.example.UsersController.java
@Autowired
private UsersRepository repository;

@RequestMapping(path = "/users", method = RequestMethod.GET)
@Transactional
public List<User> get() {
    return repository.findAll();
}
requestBody

responseBody
[
    {"id":1,"name":"kusakarikai1"},
    {"id":2,"name":"kusakarikai2"}
]

2 GET /users/id

com.example.UsersController.java
@Autowired
private UsersRepository repository;

@RequestMapping(path = "/users/{id}", method = RequestMethod.GET)
public List<User> show(Model model, @PathVariable("id") int id) {
    return repository.findById(id);
}
requestBody

responseBody
[
    {"id":1, "name":"kusakarikai1"}
]

3 POST /users

com.example.UsersController.java
@Autowired
private UsersRepository repository;

@RequestMapping(path = "/users", method = RequestMethod.POST)
@ResponseStatus(HttpStatus.CREATED)
public User create(Model model, @RequestBody User user) {
    return repository.save(user);
}
requestBody
{"name":"kusa_create"}

responseBody
[
    {"id":1, "name":"kusa_create"}
]

4 PUT /users/id

com.example.UsersController.java
@Autowired
private UsersRepository repository;

@RequestMapping(path = "/users/{id}", method = RequestMethod.PUT)
public User update(Model model, @PathVariable("id") int id, @RequestBody User user) {
    user.setId(id);
    return repository.save(user);
}
requestBody
{"name":"kusa_update"}

responseBody
[
    {"id":1, "name":"kusa_update"}
]

5 DELETE /users/id

com.example.UsersController.java
@Autowired
private UsersRepository repository;

@RequestMapping(path = "/users/{id}", method = RequestMethod.DELETE)
public void destory(Model model, @PathVariable("id") int id) {
    repository.delete(id);
}
requestBody

responceBody

ソースは以下です。
https://github.com/kaikusakari/spring_crud

14
20
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
14
20