study-note

Repository

目次

役割

Spring Data JPA

処理の流れ

@Entity → @Repository → @Service → @RestController

基本構文

Entityクラス

DBテーブルと対応

package com.example.demo.entity;

import jakarta.persistence.Entity;
import jakarta.persistence.GeneratedValue;
import jakarta.persistence.GenerationType;
import jakarta.persistence.Id;

@Entity
public class User {

  @Id
  @GeneratedValue(strategy = GenerationType.IDENTITY)
  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; }
}

Repositoryクラス(JPAインターフェース)

package com.example.demo.repository;

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

public interface UserRepository extends JpaRepository<User, Long> {
  // これだけでCRUDメソッドが自動生成される
}

Spring Data JPA

よく使うビルドインメソッド

カスタムクエリ

Spring Data JPAはメソッド名でSQLを自動生成する

使用例

Service層

package com.example.demo.service;

import org.springframework.stereotype.Service;
import com.example.demo.repository.UserRepository;
import com.example.demo.entity.User;
import java.util.List;

@Service
public class UserService {

  private final UserRepository userRepository;

  public UserService(UserRepository userRepository) {
    this.userRepository = userRepository;
  }

  public List<User> getAllUsers() {
    return userRepository.findAll();
  }

  public void addUser(User user) {
    userRepository.save(user);
  }
}

Controller層

package com.example.demo.controller;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import com.example.demo.service.UserService;

@Controller
public class UserController {

  private final UserService userService;
  public UserController(UserService userService) {
    this.userService = userService;
  }

  @GetMapping("/users")
  public String listUsers(Model model) {
    model.addAttribute("users", userService.getAllUsers());
    return "users"; // → templates/users.html
  }
}

データベース設定(H2)

application.properties

spring.datasource.url=jdbc:h2:mem:testdb
spring.datasource.driver-class-name=org.h2.Driver
spring.datasource.username=sa
spring.datasource.password=
spring.jpa.hibernate.ddl-auto=update
spring.h2.console.enabled=true

H2データベース接続情報

データベース接続(本格DB)

設定ファイルの形式

設定項目

application.yml

spring:
  datasource:
    driver-class-name: com.mysql.cj.jdbc.Driver
    url: jdbc:mysql://localhost:3306/demo_db?useSSL=false&allowPublicKeyRetrieval=true&serverTimezone=Asia/Tokyo
    username: root
    password: your_password

  jpa:
    hibernate:
      ddl-auto: update     # create / create-drop / update / validate / none
    show-sql: true          # 実行SQLをログ出力
    properties:
      hibernate:
        format_sql: true

  thymeleaf:
    cache: false            # テンプレートキャッシュ無効(開発時用)

MySQLドライバの追加

pom.xml

<dependency>
    <groupId>com.mysql</groupId>
    <artifactId>mysql-connector-j</artifactId>
</dependency>


→ 次:フォーム送信 / バリデーション