0
0

springbootを使った一般ユーザーと管理者ユーザーのDBの作成

Posted at

今回はデータベースの作成で一般ユーザーと管理者ユーザーの作成を記事にしたいと思います。

ステップ 1: ユーザーテーブルの作成
まず、ユーザーテーブルを作成します。このテーブルには、一般ユーザーと管理者ユーザーを区別するために「role」カラムを追加します。

テーブルの構造(例: MySQL)

CREATE TABLE users (
    id INT AUTO_INCREMENT PRIMARY KEY,
    username VARCHAR(50) NOT NULL,
    email VARCHAR(100) NOT NULL UNIQUE,
    password VARCHAR(255) NOT NULL,
    role ENUM('user', 'admin') DEFAULT 'user',
    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);

id: ユーザーの一意のIDです。
username: ユーザーの名前です。
email: メールアドレス(重複不可)。
password: ハッシュ化されたパスワードです。
role: 一般ユーザーはuser、管理者はadminとします。
created_at: ユーザーが作成された日時です。

ステップ 2: 初期データの挿入
次に、一般ユーザーと管理者ユーザーをデータベースに挿入します。

INSERT INTO users (username, email, password, role) VALUES
('general_user', 'user@example.com', 'password_hash1', 'user'),
('admin_user', 'admin@example.com', 'password_hash2', 'admin');

JavaのSpring Bootを使ったプロジェクトを想定して、UserクラスとUserRepository、UserService、UserControllerクラスを作成します。

  1. User エンティティクラスの作成
    まず、Userエンティティクラスを作成します。このクラスはデータベースのusersテーブルにマッピングされます。

ステップ:
Eclipseのプロジェクト内で、src/main/javaの中にentityパッケージを作成します。
Userという名前のクラスを作成します。

package com.example.demo.entity;

import javax.persistence.*;
import java.time.LocalDateTime;

@Entity
@Table(name = "users")
public class User {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;

    @Column(nullable = false, unique = true)
    private String username;

    @Column(nullable = false, unique = true)
    private String email;

    @Column(nullable = false)
    private String password;

    @Enumerated(EnumType.STRING)
    @Column(nullable = false)
    private Role role;

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

    // コンストラクタ
    public User() {
        this.createdAt = LocalDateTime.now();
    }

    // ゲッターとセッター
    public Long getId() {
        return id;
    }

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

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    public String getEmail() {
        return email;
    }

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

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    public Role getRole() {
        return role;
    }

    public void setRole(Role role) {
        this.role = role;
    }

    public LocalDateTime getCreatedAt() {
        return createdAt;
    }

    public void setCreatedAt(LocalDateTime createdAt) {
        this.createdAt = createdAt;
    }
    
    // ロールの列挙型
    public enum Role {
        USER,
        ADMIN
    }
}
  1. UserRepository インターフェースの作成
    次に、データベース操作を行うためのリポジトリインターフェースを作成します。

ステップ:
repositoryパッケージをsrc/main/javaに作成します。
UserRepositoryというインターフェースを作成します。
UserRepositoryのコード例:

package com.example.demo.repository;

import com.example.demo.entity.User;
import org.springframework.data.jpa.repository.JpaRepository;
import java.util.Optional;

public interface UserRepository extends JpaRepository<User, Long> {
    Optional<User> findByUsername(String username);
    Optional<User> findByEmail(String email);
}
  1. UserService クラスの作成
    サービスクラスを作成して、ビジネスロジックをここに記述します。ユーザーの作成や検索機能を提供します。

ステップ:
serviceパッケージを作成します。
UserServiceというクラスを作成します。
UserServiceクラスのコード例:

package com.example.demo.service;

import com.example.demo.entity.User;
import com.example.demo.repository.UserRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Optional;

@Service
public class UserService {

    @Autowired
    private UserRepository userRepository;

    public Optional<User> findUserByUsername(String username) {
        return userRepository.findByUsername(username);
    }

    public Optional<User> findUserByEmail(String email) {
        return userRepository.findByEmail(email);
    }

    public User saveUser(User user) {
        return userRepository.save(user);
    }
}
  1. UserController クラスの作成
    最後に、UserControllerクラスを作成して、ユーザーを操作するためのエンドポイントを作成します。

ステップ:
controllerパッケージを作成します。
UserControllerというクラスを作成します。
UserControllerクラスのコード例:

package com.example.demo.controller;

import com.example.demo.entity.User;
import com.example.demo.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.Optional;

@RestController
@RequestMapping("/api/users")
public class UserController {

    @Autowired
    private UserService userService;

    @PostMapping("/register")
    public ResponseEntity<User> registerUser(@RequestBody User user) {
        User savedUser = userService.saveUser(user);
        return ResponseEntity.ok(savedUser);
    }

    @GetMapping("/{username}")
    public ResponseEntity<User> getUserByUsername(@PathVariable String username) {
        Optional<User> user = userService.findUserByUsername(username);
        return user.map(ResponseEntity::ok)
                   .orElseGet(() -> ResponseEntity.notFound().build());
    }
}

クラスの作成方法の概要
Userエンティティクラスはデータベースのusersテーブルに対応し、ユーザーの役割(role)も保持。
UserRepositoryでデータベース操作を行い、ユーザー情報の取得と保存を行う。
UserServiceでビジネスロジックを管理し、リポジトリを利用してユーザー操作を行う。
UserControllerでエンドポイントを提供し、ユーザーの登録や取得を行う。

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