初期設定はたまにしかしないから、よく忘れる。
Database作る
仮にdebian系でPostgreSQLを使うものとする。
sudo apt install postgresql
sudo -u postgres psql
CREATE DATABASE demodb;
ALTER ROLE postgres WITH PASSWORD 'postgres';
マイグレーションツールを使うにしてもデータベースの設定は自分でやる。
STSを持ってきて展開する
Spring Tool Suite を https://spring.io/tools からダウンロード。
/optあたりに置くのがよいかも。
STSを起動してプロジェクトを作る
File -> New -> Spring Starter Project
デフォルトは Maven だけど Gradle のほうが好きだ。
Jar ではなく War を選ぶとよいかも。
ミニマムだと依存関係は以下のようなものか。
- JDBC API
- Spring Data JPA
- Flyway Migration
- PostgreSQL Driver
- Spring Web
application.properties
spring.datasource.driver-class-name=org.postgresql.Driver
spring.datasource.url=jdbc:postgresql://localhost:5432/demodb
spring.datasource.username=postgres
spring.datasource.password=postgres
仮にこんなテーブルが欲しいとする。
src/main/resources/db/migration/V1__Items.sql
CREATE TABLE Items (
id serial,
name varchar(15)
);
src/main/java/com/example/demo/ItemEntity.java
package com.example.demo;
import javax.persistence.*;
@Entity
@Table(name = "Items")
public class ItemEntity {
@Id
@GeneratedValue
private int id;
@Column(nullable = false)
private String name;
}
GETとPOSTだけでも実装してみる。
src/main/java/com/example/demo/ItemRepository.java
package com.example.demo;
import org.springframework.data.jpa.repository.JpaRepository;
public interface ItemRepository extends JpaRepository<ItemEntity, Integer> {
}
src/main/java/com/example/demo/ItemService.java
package com.example.demo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.util.List;
@Service
@Transactional
public class ItemService {
@Autowired
ItemRepository repository;
public ItemEntity postItem(ItemEntity item) {
return repository.save(item);
}
public List<ItemEntity> getItem() {
return repository.findAll();
}
}
src/main/java/com/example/demo/ItemController.java
package com.example.demo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import java.util.List;
@RestController
@RequestMapping("items")
public class ItemController {
@Autowired
ItemService service;
@RequestMapping(method = RequestMethod.POST)
ItemEntity postItem(@RequestBody ItemEntity item) {
return service.postItem(item);
}
@RequestMapping(method = RequestMethod.GET)
List<ItemEntity> getItem() {
return service.getItem();
}
}
とりあえずアプリを実行する
プロジェクトを選んで Run -> Run As -> Spring Boot App するとマイグレーションが実行されてテーブルが出来る。