Java | Spring Bootでよく使う実務的なコード例

Java Java
スポンサーリンク

ここでは Spring Bootでよく使う実務的なコード例 をいくつか紹介します。単なる「Hello World」ではなく、実際の業務システムでよく出てくるパターンをまとめます。


1. REST APIでデータを返す(DTO + Controller)

ユーザー情報を返すシンプルなAPI。

// DTOクラス
public class UserDto {
    private String name;
    private int age;

    public UserDto(String name, int age) {
        this.name = name;
        this.age = age;
    }

    public String getName() { return name; }
    public int getAge() { return age; }
}

// Controller
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.List;

@RestController
public class UserController {
    @GetMapping("/users")
    public List<UserDto> getUsers() {
        return List.of(
            new UserDto("Yuki", 25),
            new UserDto("Ren", 30),
            new UserDto("Aoi", 22)
        );
    }
}
Java

📌 実務ポイント

  • DTO(Data Transfer Object)を返すのが基本。
  • Spring Bootが自動でJSONに変換してくれる。

2. DBからデータを取得して返す(Spring Data JPA)

MySQLなどのDBからユーザー一覧を返すAPI。

// Entityクラス
import jakarta.persistence.Entity;
import jakarta.persistence.Id;

@Entity
public class User {
    @Id
    private Long id;
    private String name;
    private int age;

    // getter/setter省略
}

// Repository
import org.springframework.data.jpa.repository.JpaRepository;

public interface UserRepository extends JpaRepository<User, Long> {
    // 追加で findByName(String name) なども定義可能
}

// Controller
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.List;

@RestController
public class UserController {
    private final UserRepository userRepository;

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

    @GetMapping("/users")
    public List<User> getUsers() {
        return userRepository.findAll();
    }
}
Java

📌 実務ポイント

  • JpaRepository を使うとSQLを書かずにCRUDができる。
  • findAll() で全件取得。
  • 実務では findByNamefindByAgeGreaterThan のような検索メソッドを追加する。

3. サービス層を挟む(Controller → Service → Repository)

業務ロジックを整理するために Service層 を使うのが定番。

// Service
import org.springframework.stereotype.Service;
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();
    }
}

// Controller
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.List;

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

    @GetMapping("/users")
    public List<User> getUsers() {
        return userService.getAllUsers();
    }
}
Java

📌 実務ポイント

  • Controllerは「APIの入り口」だけ担当。
  • Serviceにビジネスロジックをまとめる。
  • RepositoryはDBアクセス専用。
  • この3層構造が現場でよく使われる。

4. application.properties の設定例(MySQL)

spring.datasource.url=jdbc:mysql://localhost:3306/sampledb?useSSL=false&serverTimezone=Asia/Tokyo
spring.datasource.username=root
spring.datasource.password=pass
spring.jpa.hibernate.ddl-auto=update
spring.jpa.show-sql=true

📌 実務ポイント

  • ddl-auto=update は開発用。本番では validatenone を使う。
  • show-sql=true でSQLログを確認できる。

まとめ

  • DTOを返すAPI → 基本形
  • DBから取得して返す → 実務必須
  • Controller → Service → Repository の3層構造 → 現場の定番
  • application.properties でDB設定 → 実務で必ず必要

Java
スポンサーリンク
シェアする
@lifehackerをフォローする
スポンサーリンク
タイトルとURLをコピーしました