0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

Windows11のDocker上でReact、Java、PostgresSQLの開発環境整備④

0
Posted at

本記事の目標

前回では、JPAを使う前提の環境整備をしました。
JPAは非常に強力で、②、③とその流れでやってきましたが、
今回はレガシーシステムのSQLがあって、それを使う前提での開発環境の整備をやっていきます。
DBは、②、③で作ったDBを使用しますので、JPAを使わないで、③と同じ状況に持っていく事を目標にします。

②、③のフロントエンド、バックエンドからは全然違うものになる予定なので、
①に戻って、何も入ってない環境を作っていただくのを推奨します。
テスト用DBがないと思いますので、以下を実施してください。

目指すフォルダ構成は以下となる

my-web-app/
├── backend/                  # バックエンド:Java環境
├── db-init/                  # データベースの初期化sqlファイル格納場所 ←未作成
│   └── init/                                                        ←未作成
├── db-store/                 # Dockerが使うDBデータ領域              ←未作成
├── frontend/                 # フロントエンド:React
└── compose.yml               

my-web-app直下に、db-store、db-initを作成する。
db-init以下にはinit/も作っておく。

テスト用データベースの作成とデータの準備

DBコンテナの起動時に、テスト用のデータベースの作成とデータのインサートを行うようにする
しかし、単純にCREATEしたり、INSERTするsqlを実行する様にすると、再度の起動時にエラーとなるので
そこに配慮したsqlとする。
設定としては、db-init/init/の下に、データベースの作成とデータのインサートを行うsqlファイルを配置し、
compose.ymlで、DBコンテナのinitdb.dフォルダへ配置される様にする。

2つのファイル(名前は任意ですが、アルファベット順に実行される)を配置する。
db-init/init/01_schema.sql (テーブル作成)
db-init/init/02_data.sql (初期データ投入)

テーブル作成用sql

-- 1. 顧客テーブル
CREATE TABLE IF NOT EXISTS customers (
    id SERIAL PRIMARY KEY,
    name VARCHAR(100) NOT NULL,
    email VARCHAR(100) UNIQUE
);

-- 2. 本詳細テーブル
CREATE TABLE IF NOT EXISTS books (
    id SERIAL PRIMARY KEY,
    title VARCHAR(200) NOT NULL UNIQUE,
    price INT NOT NULL
);

-- 3. 購入履歴テーブル
CREATE TABLE IF NOT EXISTS purchases (
    id SERIAL PRIMARY KEY,
    customer_id INT REFERENCES customers(id),
    book_id INT REFERENCES books(id),
    purchased_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);

データ投入用sql

-- 顧客データの登録
INSERT INTO customers (name, email) 
VALUES ('山田 太郎', 'yamada@example.com')
ON CONFLICT (email) DO NOTHING;

INSERT INTO customers (name, email) 
VALUES ('佐藤 花子', 'sato@example.com')
ON CONFLICT (email) DO NOTHING;

-- 本詳細データの登録
INSERT INTO books (title, price) 
VALUES ('Java超入門', 2800)
ON CONFLICT (title) DO NOTHING;

INSERT INTO books (title, price) 
VALUES ('Spring Boot実践ガイド', 3500)
ON CONFLICT (title) DO NOTHING;

-- 購入履歴データの登録(同じ顧客IDと本IDの組み合わせがすでに無ければ追加する)
INSERT INTO purchases (customer_id, book_id) 
SELECT 1, 1 
WHERE NOT EXISTS (SELECT 1 FROM purchases WHERE customer_id = 1 AND book_id = 1);

INSERT INTO purchases (customer_id, book_id) 
SELECT 1, 2 
WHERE NOT EXISTS (SELECT 1 FROM purchases WHERE customer_id = 1 AND book_id = 2);

INSERT INTO purchases (customer_id, book_id) 
SELECT 2, 2 
WHERE NOT EXISTS (SELECT 1 FROM purchases WHERE customer_id = 2 AND book_id = 2);

compose.ymlの修正

    volumes:
      - ./db-init/init:/docker-entrypoint-initdb.d        # この行を追加する
      - db-store:/var/lib/postgresql/data

DBコンテナを起動して

 docker compose up  -d db

顧客テーブルをSELECTする

docker compose exec db psql -U myuser -d mydatabase -c "SELECT * FROM customers;"

以下の様に表示されればOK

 id |   name    |       email        
----+-----------+--------------------
  1 | 山田 太郎 | yamada@example.com
  2 | 佐藤 花子 | sato@example.com
(2 rows)

バックエンドにDB関連の依存性の追加

DBアクセス用の依存性を追加する

plugins {
	id 'java'
	id 'org.springframework.boot' version '4.1.2'
	id 'io.spring.dependency-management' version '1.1.7'
}

group = 'com.example'
version = '0.0.1-SNAPSHOT'

java {
	toolchain {
		languageVersion = JavaLanguageVersion.of(21)
	}
}

repositories {
	mavenCentral()
}

dependencies {
	implementation 'org.springframework.boot:spring-boot-starter-webmvc'

    // この2行を追加
	implementation 'org.springframework.boot:spring-boot-starter-jdbc'
    implementation 'org.mybatis.spring.boot:mybatis-spring-boot-starter:4.1.0'

	runtimeOnly 'org.postgresql:postgresql'

	testImplementation 'org.springframework.boot:spring-boot-starter-webmvc-test'
	testRuntimeOnly 'org.junit.platform:junit-platform-launcher'
}

tasks.named('test') {
	useJUnitPlatform()
}

バックエンドにデータベースのテーブルに対応する「Entityクラス」を作る

① 作成したテーブルに対応するJavaのクラス(Entity)を作成する。
これにより、Javaのオブジェクト操作がそのままSQL(テーブル)にマッピングされる。
src/main/java/com/example/demo/
直下にentity/フォルダを作成し、その下にBook.javaを作成し以下を記述する

package com.example.demo.entity;

public class Book {
    private Long id;
    private String title;
    private Integer price;

    // --- Getter / Setter ---
    public Long getId() { return id; }
    public void setId(Long id) { this.id = id; }

    public String getTitle() { return title; }
    public void setTitle(String title) { this.title = title; }

    public Integer getPrice() { return price; }
    public void setPrice(Integer price) { this.price = price; }
}

同様にCustomer.javaを作成し以下を記述する

package com.example.demo.entity;

public class Customer {
    private Long id;
    private String name;
    private String email;

    // --- Getter / Setter ---
    public Long getId() { return id; }
    public void setId(Long id) { this.id = id; }

    public String getName() { return name; }
    public void setName(String name) { this.name = name; }

    public String getEmail() { return email; }
    public void setEmail(String email) { this.email = email; }
}

同様にPurchase.javaを作成し以下を記述する

package com.example.demo.entity;

import java.time.LocalDateTime;

public class Purchase {
    private Long id;
    private Long customerId;
    private Long bookId;
    private LocalDateTime purchasedAt;

    // 結合して取得する本の情報や顧客情報を持たせる場合
    private String bookTitle;
    private Integer bookPrice;

    // --- Getter / Setter ---
    public Long getId() { return id; }
    public void setId(Long id) { this.id = id; }

    public Long getCustomerId() { return customerId; }
    public void setCustomerId(Long customerId) { this.customerId = customerId; }
    
    public Long getBookId() { return bookId; }
    public void setBookId(Long bookId) { this.bookId = bookId; }
    
    public LocalDateTime getPurchasedAt() { return purchasedAt; }
    public void setPurchasedAt(LocalDateTime purchasedAt) { this.purchasedAt = purchasedAt; }
    
    public String getBookTitle() { return bookTitle; }
    public void setBookTitle(String bookTitle) { this.bookTitle = bookTitle; }
    
    public Integer getBookPrice() { return bookPrice; }
    public void setBookPrice(Integer bookPrice) { this.bookPrice = bookPrice; }
}

バックエンドのJava側のインターフェースとSQLを準備する

目指すフォルダ構成としては以下になる

backend/
 └── src/
      └── main/
           ├── java/
           │    └── com/example/demo/
           │         ├── controller/
           │         │    ├── BookController.java      # Bookコントローラ
           │         │    ├── CustomerController.java  # Customerコントローラ
           │         │    └── PurchaseController.java  # Purchaseコントローラ
           │         ├── entity/
           │         │    ├── Book.java                # Bookエンティティ
           │         │    ├── Customer.java            # Customerエンティティ
           │         │    └── Purchase.java            # Purchaseエンティティ
           │         └── repository/
           │              ├── BookMapper.java          # Bookインターフェース
           │              ├── CustomerMapper.java      # Customerインターフェース
           │              └── PurchaseMapper.java      # Purchaseインターフェース
           └── resources/
                └── sql/
                     └── CustomerMapper.xml            # BookのSQL
                     └── CustomerMapper.xml            # CustomerのSQL
                     └── CustomerMapper.xml            # PurchaseのSQL

SQLのローダの作成

SQLをファイルとして作成する事にしたので、Java側でそのSQLファイルのローダが必要になる
src/main/java/com/example/demo/util/のフォルダを作成し、SqlLoader.javaを作成する
SqlLoader.javaは以下の様に記述する

package com.example.demo.util;

import org.springframework.core.io.ClassPathResource;
import org.springframework.util.StreamUtils;

import java.io.IOException;
import java.nio.charset.StandardCharsets;

public class SqlLoader {

    public static String load(String sqlFileName) {
        try {
            // src/main/resources/sql/ 配下のファイルを指定
            ClassPathResource resource = new ClassPathResource("sql/" + sqlFileName);
            return StreamUtils.copyToString(resource.getInputStream(), StandardCharsets.UTF_8);
        } catch (IOException e) {
            throw new RuntimeException("外部SQLファイルの読み込みに失敗しました: " + sqlFileName, e);
        }
    }
}

バックエンドのJava側のインターフェースの作成

バックエンドのJava側のインターフェースをjavaで記述する
① Java側インターフェース:BookMapper.java
src/main/java/com/example/demo/repository/BookMapper.java を作成する
@Mapper アノテーションを付与したインターフェースにする
 ※PAのときと違い、JpaRepository を継承しない

package com.example.demo.repository;

import com.example.demo.entity.Book;
import com.example.demo.util.SqlLoader;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.SelectProvider;

import java.util.List;

@Mapper
public interface BookMapper {

    @SelectProvider(type = BookSqlProvider.class, method = "selectAllSql")
    List<Book> selectAll();

    // SQLプロバイダクラス(外部の .sql ファイルを読み込んで返す)
    class BookSqlProvider {
        public String selectAllSql() {
            // src/main/resources/sql/Book_selectAll.sql を読み込む
            return SqlLoader.load("Book_selectAll.sql");
        }
    }
}

② Java側インターフェース:CustomerMapper.java
src/main/java/com/example/demo/repository/CustomerMapper.java を作成する
@Mapper アノテーションを付与したインターフェースにする

package com.example.demo.repository;

import com.example.demo.entity.Customer;
import com.example.demo.util.SqlLoader;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.SelectProvider;

import java.util.List;

@Mapper
public interface CustomerMapper {

    @SelectProvider(type = CustomerSqlProvider.class, method = "selectAllSql")
    List<Customer> selectAll();

    // SQLプロバイダクラス(外部の .sql ファイルを読み込んで返す)
    class CustomerSqlProvider {
        public String selectAllSql() {
            // src/main/resources/sql/Customer_selectAll.sql を読み込む
            return SqlLoader.load("Customer_selectAll.sql");
        }
    }
}

③ Java側インターフェース:PurchaseMapper.java
src/main/java/com/example/demo/repository/PurchaseMapper.java を作成する
@Mapper アノテーションを付与したインターフェースにする

package com.example.demo.repository;

import com.example.demo.entity.Purchase;
import com.example.demo.util.SqlLoader;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.SelectProvider;
import org.apache.ibatis.annotations.Param;

import java.util.List;

@Mapper
public interface PurchaseMapper {

    @SelectProvider(type = PurchaseSqlProvider.class, method = "selectByCustomerIdSql")
    List<Purchase> selectByCustomerId(@Param("customerId") Long customerId);

    class PurchaseSqlProvider {
        public String selectByCustomerIdSql() {
            return SqlLoader.load("Purchase_selectByCustomer.sql");
        }
    }
}

各SQLの作成

src/main/resources/sql/フォルダを作成し、各SQLファイルを格納する
① Bookの一覧取得:Book_selectAll.sqlを作成する

SELECT 
    id, 
    title, 
    price 
FROM books

② Bookの一覧取得:Customer_selectAll.sqlを作成する

SELECT 
    id, 
    name, 
    email 
FROM customers

③ Bookの一覧取得:Purchase_selectByCustomer.sqlを作成する

SELECT 
    p.id AS id,
    p.customer_id AS customerId,
    p.book_id AS bookId,
    p.purchased_at AS purchasedAt,
    b.title AS bookTitle,
    b.price AS bookPrice
FROM purchases p
JOIN books b ON p.book_id = b.id
WHERE p.customer_id = #{customerId}

コントローラを整備する

本の一覧情報、顧客一覧情報、顧客毎の履歴情報へアクセスするためのコントローラの整備をする

本の一覧情報を取得するコントローラの作成

本の一覧情報へアクセスするコントローラを作成する
src/main/java/com/example/demo/controller/
直下にBookController.javaを作成し以下を記述する

package com.example.demo.controller;

import com.example.demo.entity.Book;
import com.example.demo.repository.BookMapper;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

@RestController
@RequestMapping("/api")
public class BookController {

    private final BookMapper bookMapper;

    public BookController(BookMapper bookMapper) {
        this.bookMapper = bookMapper;
    }

    @GetMapping("/books")
    public List<Book> getAllBooks() {
        return bookMapper.selectAll();
    }
}

顧客の一覧情報を取得するコントローラの作成

顧客の一覧情報へアクセスするコントローラを作成する
src/main/java/com/example/demo/controller/
直下にCustomerController.javaを作成し以下を記述する

package com.example.demo.controller;

import com.example.demo.entity.Customer;
import com.example.demo.repository.CustomerMapper;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

@RestController
@RequestMapping("/api")
public class CustomerController {

    private final CustomerMapper customerMapper;

    public CustomerController(CustomerMapper customerMapper) {
        this.customerMapper = customerMapper;
    }

    @GetMapping("/customers")
    public List<Customer> getCustomers() {
        return customerMapper.selectAll();
    }
}

顧客毎の購入履歴情報を取得するコントローラの作成

フロントエンドから GET /api/customers/{customerId}/purchases というURLでリクエストを受け取り、
上のリポジトリを呼び出してJSONを返すコントローラを作成する
src/main/java/com/example/demo/controller/
直下にPurchaseController.javaを作成し以下を記述する

package com.example.demo.controller;

import com.example.demo.entity.Purchase;
import com.example.demo.repository.PurchaseMapper;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

@RestController
@RequestMapping("/api")
public class PurchaseController {

    private final PurchaseMapper purchaseMapper;

    public PurchaseController(PurchaseMapper purchaseMapper) {
        this.purchaseMapper = purchaseMapper;
    }

    // 顧客ID指定の購入履歴取得用エンドポイント
    // 例: GET /api/customers/1/purchases
    @GetMapping("/customers/{customerId}/purchases")
    public List<Purchase> getPurchasesByCustomer(@PathVariable Long customerId) {
        return purchaseMapper.selectByCustomerId(customerId);
    }
}

フロントエンドの整備

大規模開発を意識して、ルーティングを使用するので、
フロントエンド側に、react-router-domを追加する
フロントエンドを起動して

docker compose up -d frontend

react-router-domを追加する

docker compose exec frontend npm install react-router-dom

フォルダ構成の変更

ルーティングするのに合わせて、各機能毎の画面を作成するので、フォルダ構成は以下の様になる

src/
 ┣ pages/
 ┃  ┣ Home.tsx             # メニュー画面
 ┃  ┣ CustomerList.tsx     # 顧客一覧画面
 ┃  ┣ CustomerPurchases.tsx# 顧客ごとの購入履歴画面
 ┃  ┗ BookList.tsx         # 在庫確認画面(本の一覧)
 ┗ App.tsx                 # ルーティング設定のみを担当

各画面の作成

① メニュー画面 (src/pages/Home.tsx)
メニュー画面には、顧客知覧画面と在庫一覧画面へのメニューボタンを配置する
Home.tsxは以下の様に記述する

import { Container, Typography, Button, Box, Stack } from '@mui/material';
import { useNavigate } from 'react-router-dom';

export default function Home() {
  const navigate = useNavigate();

  return (
    <Container maxWidth="sm" sx={{ mt: 8, textAlign: 'center' }}>
      <Typography variant="h4" gutterBottom>
        本屋の管理システム メニュー
      </Typography>
      <Box sx={{ mt: 4 }}>
        <Stack spacing={2}>
          <Button 
            variant="contained" 
            size="large" 
            onClick={() => navigate('/customers')}
          >
            顧客一覧画面へ
          </Button>
          <Button 
            variant="contained" 
            size="large" 
            color="secondary" 
            onClick={() => navigate('/books')}
          >
            在庫確認(本一覧)へ
          </Button>
        </Stack>
      </Box>
    </Container>
  );
}

② 顧客一覧画面 (src/pages/CustomerList.tsx)
各顧客の行に「購入履歴」ボタンを置き、クリックすると /customers/{id}/purchases へ飛ぶようにする
CustomerList.tsxは以下の様に記述する

import { useEffect, useState } from 'react';
import { Container, Typography, Table, TableBody, TableCell, TableContainer, TableHead, TableRow, Paper, CircularProgress, Button, Box } from '@mui/material';
import { useNavigate } from 'react-router-dom';

interface Customer {
  id: number;
  name: string;
  email: string;
}

export default function CustomerList() {
  const [customers, setCustomers] = useState<Customer[]>([]);
  const [loading, setLoading] = useState<boolean>(true);
  const [error, setError] = useState<string | null>(null);
  const navigate = useNavigate();

  useEffect(() => {
    fetch('/api/customers')
      .then((res) => {
        if (!res.ok) throw new Error('顧客データの取得に失敗しました');
        return res.json();
      })
      .then((data) => {
        setCustomers(data);
        setLoading(false);
      })
      .catch((err) => {
        setError(err.message);
        setLoading(false);
      });
  }, []);

  return (
    <Container maxWidth="md" sx={{ mt: 5 }}>
      <Box display="flex" justifyContent="space-between" alignItems="center" mb={3}>
        <Button variant="outlined" onClick={() => navigate('/')}>
          ← メニューに戻る
        </Button>
        <Typography variant="h4">顧客一覧</Typography>
        <div />
      </Box>

      {loading && <CircularProgress />}
      {error && <Typography color="error">{error}</Typography>}

      {!loading && !error && (
        <TableContainer component={Paper} elevation={3}>
          <Table>
            <TableHead sx={{ backgroundColor: '#f5f5f5' }}>
              <TableRow>
                <TableCell><b>ID</b></TableCell>
                <TableCell><b>名前</b></TableCell>
                <TableCell><b>メールアドレス</b></TableCell>
                <TableCell align="center"><b>操作</b></TableCell>
              </TableRow>
            </TableHead>
            <TableBody>
              {customers.map((c) => (
                <TableRow key={c.id}>
                  <TableCell>{c.id}</TableCell>
                  <TableCell>{c.name}</TableCell>
                  <TableCell>{c.email}</TableCell>
                  <TableCell align="center">
                    <Button 
                      variant="contained" 
                      size="small"
                      onClick={() => navigate(`/customers/${c.id}/purchases`)}
                    >
                      購入履歴を見る
                    </Button>
                  </TableCell>
                </TableRow>
              ))}
            </TableBody>
          </Table>
        </TableContainer>
      )}
    </Container>
  );
}

③ 顧客ごとの購入履歴画面 (src/pages/CustomerPurchases.tsx)
URLに含まれる :id を useParams で取得し、先ほどバックエンドで作った /api/customers/{id}/purchases を叩いて絞り込み表示する
CustomerPurchases.tsxは以下の様に記述する

import { useEffect, useState } from 'react';
import { Container, Typography, Table, TableBody, TableCell, TableContainer, TableHead, TableRow, Paper, CircularProgress, Button, Box } from '@mui/material';
import { useParams, useNavigate } from 'react-router-dom';

// ★ フラットなJSON構造に合わせて型定義を修正
interface Purchase {
  id: number;
  bookId: number;
  bookTitle: string;   // 直接プロパティとして受け取る
  bookPrice: number;   // 直接プロパティとして受け取る
  purchasedAt: string;
}

export default function CustomerPurchases() {
  const { id } = useParams<{ id: string }>();
  const [purchases, setPurchases] = useState<Purchase[]>([]);
  const [loading, setLoading] = useState<boolean>(true);
  const [error, setError] = useState<string | null>(null);
  const navigate = useNavigate();

  useEffect(() => {
    fetch(`/api/customers/${id}/purchases`)
      .then((res) => {
        if (!res.ok) throw new Error('購入履歴の取得に失敗しました');
        return res.json();
      })
      .then((data) => {
        setPurchases(data);
        setLoading(false);
      })
      .catch((err) => {
        setError(err.message);
        setLoading(false);
      });
  }, [id]);

  return (
    <Container maxWidth="md" sx={{ mt: 5 }}>
      <Box display="flex" justifyContent="space-between" alignItems="center" mb={3}>
        <Button variant="outlined" onClick={() => navigate('/customers')}>
          ← 顧客一覧に戻る
        </Button>
        <Typography variant="h4">購入履歴 (顧客ID: {id})</Typography>
        <div />
      </Box>

      {loading && <CircularProgress />}
      {error && <Typography color="error">{error}</Typography>}

      {!loading && !error && (
        purchases.length === 0 ? (
          <Typography align="center" sx={{ mt: 4 }} color="textSecondary">
            この顧客の購入履歴はありません。
          </Typography>
        ) : (
          <TableContainer component={Paper} elevation={3}>
            <Table>
              <TableHead sx={{ backgroundColor: '#f5f5f5' }}>
                <TableRow>
                  <TableCell><b>履歴ID</b></TableCell>
                  <TableCell><b>購入した本</b></TableCell>
                  <TableCell><b>価格</b></TableCell>
                  <TableCell><b>購入日時</b></TableCell>
                </TableRow>
              </TableHead>
              <TableBody>
                {purchases.map((p) => (
                  <TableRow key={p.id}>
                    <TableCell>{p.id}</TableCell>
                    {/* ★ p.book.title ではなく直接参照する */}
                    <TableCell>{p.bookTitle}</TableCell>
                    <TableCell>{p.bookPrice} 円</TableCell>
                    <TableCell>{p.purchasedAt}</TableCell>
                  </TableRow>
                ))}
              </TableBody>
            </Table>
          </TableContainer>
        )
      )}
    </Container>
  );
}

④ 在庫確認画面 (src/pages/BookList.tsx)
メニュー画面の「在庫一覧」ボタンをクリックすると本画面を開く
BookList.tsxは以下の様に記述する

import { useEffect, useState } from 'react';
import { Container, Typography, Table, TableBody, TableCell, TableContainer, TableHead, TableRow, Paper, CircularProgress, Button, Box } from '@mui/material';
import { useNavigate } from 'react-router-dom';

interface Book {
  id: number;
  title: string;
  price: number;
}

export default function BookList() {
  const [books, setBooks] = useState<Book[]>([]);
  const [loading, setLoading] = useState<boolean>(true);
  const [error, setError] = useState<string | null>(null);
  const navigate = useNavigate();

  useEffect(() => {
    fetch('/api/books')
      .then((res) => {
        if (!res.ok) throw new Error('在庫データの取得に失敗しました');
        return res.json();
      })
      .then((data) => {
        setBooks(data);
        setLoading(false);
      })
      .catch((err) => {
        setError(err.message);
        setLoading(false);
      });
  }, []);

  return (
    <Container maxWidth="md" sx={{ mt: 5 }}>
      <Box display="flex" justifyContent="space-between" alignItems="center" mb={3}>
        <Button variant="outlined" onClick={() => navigate('/')}>
          ← メニューに戻る
        </Button>
        <Typography variant="h4">在庫一覧(本)</Typography>
        <div />
      </Box>

      {loading && <CircularProgress />}
      {error && <Typography color="error">{error}</Typography>}

      {!loading && !error && (
        <TableContainer component={Paper} elevation={3}>
          <Table>
            <TableHead sx={{ backgroundColor: '#f5f5f5' }}>
              <TableRow>
                <TableCell><b>ID</b></TableCell>
                <TableCell><b>タイトル</b></TableCell>
                <TableCell><b>価格</b></TableCell>
              </TableRow>
            </TableHead>
            <TableBody>
              {books.map((b) => (
                <TableRow key={b.id}>
                  <TableCell>{b.id}</TableCell>
                  <TableCell>{b.title}</TableCell>
                  <TableCell>{b.price}円</TableCell>
                </TableRow>
              ))}
            </TableBody>
          </Table>
        </TableContainer>
      )}
    </Container>
  );
}

ルーティングの設定

作成したすべての画面を App.tsx でルーティングとして繋ぎ合わせる
App.tsxを以下の様に記述する

import { BrowserRouter as Router, Routes, Route } from 'react-router-dom';
import Home from './pages/Home';
import CustomerList from './pages/CustomerList';
import CustomerPurchases from './pages/CustomerPurchases';
import BookList from './pages/BookList';

function App() {
  return (
    <Router>
      <Routes>
        {/* メニュー画面 */}
        <Route path="/" element={<Home />} />
        {/* 顧客一覧画面 */}
        <Route path="/customers" element={<CustomerList />} />
        {/* 特定の顧客の購入履歴画面(:idでURLパラメータを受け取る) */}
        <Route path="/customers/:id/purchases" element={<CustomerPurchases />} />
        {/* 在庫確認画面 */}
        <Route path="/books" element={<BookList />} />
      </Routes>
    </Router>
  );
}

export default App;

CORSエラーの回避

Docker環境では、フロントエンド(React/Vite: localhost:5173)から
バックエンド(Spring Boot: localhost:8080)へ直接 fetch しようとすると、
ポート番号が異なるため CORS(クロスドorigin)エラー に阻まれることがある。
これを回避するため、vite.config.tsにViteのプロキシ設定 を入れておく

import react from '@vitejs/plugin-react'
import { defineConfig } from 'vite'

// https://vite.dev/config/
export default defineConfig({
  plugins: [react()],
  server: {
    host: true, // コンテナの外(パソコンのブラウザ)からのアクセスを許可
    proxy: {
      '/api': {
        target: 'http://backend:8080', // Docker環境内のバックエンドサービス名
        changeOrigin: true,
      },
    },
  },
})

すべてのコンテナを起動して、以下を実行してフロントエンドからアクセスしてみる
以下にアクセスする。
http://localhost:5173/

想定したメニュー画面が表示され、各ボンタンの動作が確認できればOK

仕様の追加に伴うバックエンドの整備、フロントエンドの整備についてイメージついたかなと思います。

お疲れ様でした。

いったんは、ここまでで基本的な所は網羅できたと思います。

0
0
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
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?