PostgreSQL と Spring Data JPA を使用してSpring Boot でアプリを作成してみた【 RESTful API 】

## 1. start.spring.io でプロジェクトを作成する

(1) ブラウザを開き、(https://start.spring.io/) を入力し、開く
(2) 下記を入力し、Dependenciesで下記を選択し、『GENERATE』ボタンを押す

- Project: Maven
- Language: Java
- SpringBoot: 3.3.2

- Group: com.developer
- Artifact: employee-management
- Name : employee-management
- Description: Build Restful API with JPA and Postgresql
- Package name: com.developer.employee-management

Dependencies
- Spring Web
- Spring Data JPA
- PostgreSQL Driver

## 2. データベースの作成とデータベースへの接続する

(1)postgresqlデータベースを作成する

(2)application.propertiesを編集する

```src/main/resources/application.properties
## connect to database
spring.datasource.driver-class-name=org.postgresql.Driver
spring.datasource.url=jdbc:postgresql://localhost:5432/employeedb
spring.datasource.username=postgres
spring.datasource.password=p@ssw0rd

## JPA Config
spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.PostgreSQLDiaLect
spring.jpa.hibernate.ddl-auto=update
spring.jpa.show-sql=true
spring.jpa.properties.hibernate.format_sql=true
```
## 3. エンティティを作成し、データベースにテーブルを自動作成する

(1) java/com.developer/employee_managementにentityパッケージと
EmployeeEntity.javaを作成する

```java/com.developer/employee_management/entity/EmployeeEntity.java
package com.developer.employee_management.entity;

import jakarta.persistence.*;
import java.util.Date;

@Entity
@Table(name = "mt_employee")
public class EmployeeEntity {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name = "emp_id")

    private Long id;

    @Column(name = "name")
    private String name;

    @Column(name = "gender")
    private String gender;

    @Column(name = "date_of_birth")
    private Date dateOfBirth;

    @Column(name = "address")
    private String address;

    public EmployeeEntity(Long id, String name, String gender, Date dateOfBirth, String address) {
        this.id = id;
        this.name = name;
        this.gender = gender;
        this.dateOfBirth = dateOfBirth;
        this.address = address;
    }

    public Long getId() {
        return id;
    }

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

    public String getName() {
        return name;
    }
}
```

## 4.リポジトリを作成する

(1)java/com.developer/employee_managementにrepositoryパッケージと
EmployeeRepository.javaを作成する

```java/com.developer/employee_management/repository/EmployeeRepository.java
package com.developer.employee_management.repository;

import com.developer.employee_management.entity.EmployeeEntity;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;

@Repository
public interface EmployeeRepository extends JpaRepository<EmployeeEntity, Long> {

}
```

## 5. サービスの作成とサービスの実装する

(1) java/com.developer/employee_managementにserviceパッケージと
EmployeeService.javaを作成する

```java/com.developer/employee_management/service/EmployeeService.java
package com.developer.employee_management.service;

import com.developer.employee_management.entity.EmployeeEntity;
import java.util.List;

public interface EmployeeService {
    List<EmployeeEntity> findAllEmployee();

    EmployeeEntity findById(Long id);

    EmployeeEntity saveEmployee(EmployeeEntity employeeEntity);

    EmployeeEntity updateEmployee(EmployeeEntity employeeEntity);

    void deleteEmployee(Long id);
}
```

(2) java/com.developer/employee_management/serviceにimplパッケージと
EmployeeService.javaを作成する

``` java/com.developer/employee_management/service/impl/EmployeeService.java
package com.developer.employee_management.service.impl;

import com.developer.employee_management.entity.EmployeeEntity;
import com.developer.employee_management.repository.EmployeeRepository;
import com.developer.employee_management.service.EmployeeService;
import org.springframework.stereotype.Service;

import java.util.*;

@Service
public class EmployeeServiceImpl implements EmployeeService {

    private final EmployeeRepository employeeRepository;

    public EmployeeServiceImpl(EmployeeRepository employeeRepository) {
        this.employeeRepository = employeeRepository;
    }

    @Override
    public List<EmployeeEntity> findAllEmployee() {
        return employeeRepository.findAll();
    }

    @Override
    public Optional<EmployeeEntity> findById(Long id) {
        return employeeRepository.findById(id);
    }

    @Override
    public EmployeeEntity saveEmployee(EmployeeEntity employeeEntity) {
        return employeeRepository.save(employeeEntity);
    }

    @Override
    public EmployeeEntity updateEmployee(EmployeeEntity employeeEntity) {
        return employeeRepository.save(employeeEntity);
    }

    @Override
    public void deleteEmployee(Long id) {
        employeeRepository.deleteById(id);
    }
}
```

## 6. Controllerを作成する

(1) java/com.developer/employee_managementにcontrollerパッケージと
EmployeeController.javaを作成する

```java/com.developer/employee_management/controller/EmployeeController.java
package com.developer.employee_management.controller;

import com.developer.employee_management.entity.EmployeeEntity;
import com.developer.employee_management.service.EmployeeService;

import org.apache.el.stream.Optional;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/employee")
public class EmployeeController {

    private final EmployeeService employeeService;

    public EmployeeController(EmployeeService employeeService) {
        this.employeeService = employeeService;
    }

    @GetMapping
    public List<EmployeeEntity> findAllEmployee() {
        return employeeService.findAllEmployee();
    }

    @GetMapping("/{id}")
    public Optional<EmployeeEntity> findEmployeeById(@PathVariable("id") Long id) {
        return employeeService.findById(id);
    }

    @PostMapping
    public EmployeeEntity saveEmployee(@RequestBody EmployeeEntity employeeEntity) {
        return employeeService.saveEmployee(employeeEntity);
    }

    @PutMapping
    public EmployeeEntity updateEmployee(@RequestBody EmployeeEntity employeeEntity) {
        return employeeService.saveEmployee(employeeEntity);
    }

    @DeleteMapping("/{id}")
    public void deleteEmployee(@PathVariable("id") Long id) {
        employeeService.deleteEmployee(id);
    }
}
```


## 参考サイト
[Build Restful API With Spring Boot using PostgreSQL and Spring Data JPA | Full Course for Beginner](https://www.youtube.com/watch?v=ZTxn38j4DJE&list=WL&index=352)