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?

2.SpringBoot側に投稿に関するテーブルの作成

Posted at

📝 Spring BootでPostsテーブルを扱うための実装手順

このドキュメントでは、以下のPostsテーブル定義に基づいて、Spring Bootで使用するための Entity・Repository・Controller を作成します。


🧹 デフォルトファイルの削除

Spring Boot プロジェクト作成時に自動生成される DemoApplication.java は使用しないため、削除して構いません
ただし、代わりにエントリポイント用のクラス(例: SimpleCrudSpringApplication.java)を別途作成してください(必要であれば)。


✅ Postsテーブル定義(前提)

カラム名 データ型 内容 制限・特徴
id BIGINT (UNSIGNED) 投稿ID(自動採番) 主キー
user_id BIGINT (UNSIGNED) 投稿者のユーザーID 外部キー(users.id 参照)、NULL不可
title VARCHAR(255) 投稿タイトル NULL不可
content TEXT 投稿内容の詳細 NULL不可
created_at TIMESTAMP 作成日時 自動追加
updated_at TIMESTAMP 更新日時 自動追加
deleted_at TIMESTAMP 削除日時 自動追加

📦 1. Entity の作成(Post.java

package com.example.simple_crud_spring.model;

import jakarta.persistence.*;

import java.time.LocalDateTime;

@Entity
@Table(name = "posts")
public class Post {
    
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;

    @Column(name = "user_id", nullable = false)
    private Long userId;

    @Column(nullable = false, length = 255)
    private String title;

    @Column(nullable = false, columnDefinition = "TEXT")
    private String content;

    @Column(name = "created_at", updatable = false)
    private LocalDateTime createdAt;

    @Column(name = "updated_at")
    private LocalDateTime updatedAt;

    @Column(name = "deleted_at")
    private LocalDateTime deletedAt;

    @PrePersist
    protected void onCreate(){
        this.createdAt = LocalDateTime.now();
        this.updatedAt = LocalDateTime.now();
    }

    @PreUpdate
    protected void onUpdate(){ 
        this.updatedAt = LocalDateTime.now();
    }

    public Long getId() {
        return id;
    }

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

    public Long getUserId() {
        return userId;
    }

    public void setUserId(Long userId) {
        this.userId = userId;
    }

    public String getTitle() {
        return title;
    }

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

    public String getContent() {
        return content;
    }

    public void setContent(String content) {
        this.content = content;
    }

    public LocalDateTime getCreatedAt() {
        return createdAt;
    }

    public void setCreatedAt(LocalDateTime createdAt) {
        this.createdAt = createdAt;
    }

    public LocalDateTime getUpdatedAt() {
        return updatedAt;
    }

    public void setUpdatedAt(LocalDateTime updatedAt) {
        this.updatedAt = updatedAt;
    }

    public LocalDateTime getDeletedAt() {
        return deletedAt;
    }

    public void setDeletedAt(LocalDateTime deletedAt) {
        this.deletedAt = deletedAt;
    }

    
}

📚 2. Repository の作成(PostRepository.java

package com.example.simple_crud_spring.repository;

import com.example.simple_crud_spring.model.Post;
import org.springframework.data.jpa.repository.JpaRepository;

public interface PostRepository extends JpaRepository<Post, Long>{
    // 追加のクエリメソッドは必要に応じて
}


🌐 3. Controller の作成(PostController.java

package com.example.simple_crud_spring.controller;

import com.example.simple_crud_spring.model.Post;
import com.example.simple_crud_spring.repository.PostRepository;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@CrossOrigin(origins = "*")
@RestController
@RequestMapping("/api/posts")
public class PostController{
    
    private final PostRepository postRepository;

    public PostController(PostRepository postRepository){
        this.postRepository = postRepository;
    }

    @GetMapping
    public List<Post> getAll(){
        return postRepository.findAll();
    }

    @PostMapping
    public Post create(@RequestBody Post post){
        return postRepository.save(post);
    }

    @GetMapping("/{id}")
    public Post getById(@PathVariable Long id){
        return postRepository.findById(id).orElse(null);
    }

    @PutMapping("/{id}")
    public Post update(@PathVariable Long id, @RequestBody Post updatedPost){
        return postRepository.findById(id)
            .map(post -> {
                post.setTitle(updatedPost.getTitle());
                post.setContent(updatedPost.getContent());
                post.setUserId(updatedPost.getUserId());
                return postRepository.save(post);
            })
            .orElse(null);
    }
}

テーブルの作成

  • gradlew.bat bootRunを中断し、再度実行することでテーブルが作成されます。
  • ※カラム名などを間違えたなどの理由から変更したい場合、一度テーブルをA5M2上でドロップし、再度gradlew.bat bootRunを中断し、実行することでテーブルが作成されます。
  • A5M2上で表示されるカラム名が変わらない場合がありますが、A5M2を再起動すると変更後の表示になります。

✅ 完了後に確認できること

  • /api/posts にアクセスして、GET・POST・PUT・DELETE のAPIが使用可能になります。
  • Reactから fetch("http://localhost:8080/api/posts") で呼び出すことでデータ連携が可能になります。

🎀 補足

  • @PrePersist および @PreUpdate により、created_atupdated_at を自動設定します。
  • deleted_at は現時点で未使用(論理削除未実装)ですが、必要に応じて @SQLDelete などを導入してください。
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?