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?

More than 1 year has passed since last update.

Spring Boot + Kotlin でRESTアプリ作成ハンズオン2

Last updated at Posted at 2023-06-16

前回↓

次回↓

2.DBの導入

2-1. H2 Database Engineを導入する

  • build.gradleのdependenciesに以下のようにJPAとH2を追加します。
build.gradle(一部)
plugins {
	id 'org.springframework.boot' version '2.7.12'
	id 'io.spring.dependency-management' version '1.0.15.RELEASE'
	id 'org.jetbrains.kotlin.jvm' version '1.6.21'
	id 'org.jetbrains.kotlin.plugin.spring' version '1.6.21'
 	id 'org.jetbrains.kotlin.plugin.jpa' version '1.6.21' // <-- 追加
}
build.gradle(一部)
dependencies {
	implementation 'org.springframework.boot:spring-boot-starter-web'
	implementation 'com.fasterxml.jackson.module:jackson-module-kotlin'
	implementation 'org.jetbrains.kotlin:kotlin-reflect'
	implementation 'org.springframework.boot:spring-boot-starter-data-jpa'		// <-- 追加
	runtimeOnly 'com.h2database:h2'		// <-- 追加
	developmentOnly 'org.springframework.boot:spring-boot-devtools'
	testImplementation 'org.springframework.boot:spring-boot-starter-test'
}
  • 追加したら、gradleをリロードしてください。

image.png

2-2. application.ymlにDBの設定を追加する

  • application.propertiesapplication.yml にリネームします。
  • application.properties を右クリック → Refactor → Rename → application.yml

image.png

image.png

  • application.yml に以下の設定を追加します。
  • DB_CLOSE_DELAYは、アプリケーション終了時にDBをクローズしないようにするための設定です。
  • DB_CLOSE_ON_EXITは、VM終了時にDBをクローズしないようにするための設定です。
  • sql.init.data-locationは、初期データ投入SQLファイルを指定します。
  • defer-datasource-initializationはDDLをエンティティクラスから自動作成するかどうかです。
application.yml
spring:
  datasource:
    url: jdbc:h2:mem:tododb;DB_CLOSE_DELAY=-1;DB_CLOSE_ON_EXIT=FALSE
    driver-class-name: org.h2.Driver
    username: sa
    password:
  sql:
    init:
      encoding: UTF-8
      data-locations: classpath:data.sql
      enabled: true
  h2:
    console:
      enabled: true
  jpa:
    defer-datasource-initialization: true
  • com.example.demo に エンティティクラス Todo.kt を新規作成します。
Todo.kt
package com.example.demo

import java.time.OffsetDateTime
import javax.persistence.*

@Entity
@Table(name = "todo")
class Todo(

        @Id
        @GeneratedValue(strategy = GenerationType.IDENTITY)
        var id: Long? = null,

        @Column(name = "title")
        var title: String,

        @Column(name = "description")
        var description: String?,

        @Column(name = "is_completed")
        var isCompleted: Boolean,

        @Column(name = "created_at")
        var createdAt: OffsetDateTime,

        @Column(name = "updated_at")
        var updatedAt: OffsetDateTime
)
  • data.sqlresources 配下に作成します。

image.png

  • 内容は何でもいいです。
data.sql
INSERT INTO todo (title, description, is_completed, created_at, updated_at) VALUES
('買い物リスト', '牛乳, パン, りんご', false, CURRENT_TIMESTAMP(), CURRENT_TIMESTAMP()),
('郵便局に行く', '郵便局で小包を受け取る', false, CURRENT_TIMESTAMP(), CURRENT_TIMESTAMP()),
('家賃の支払い', '家賃を振り込む', true, CURRENT_TIMESTAMP(), CURRENT_TIMESTAMP()),
('ジムに行く', '週に2回筋トレ&カーディオ', true, CURRENT_TIMESTAMP(), CURRENT_TIMESTAMP()),
('映画を観る', '新作の映画を観に行く', false, CURRENT_TIMESTAMP(), CURRENT_TIMESTAMP());

image.png

  • SELECT * FROM TODO を実行すると、データが入っていることが確認できました。

image.png

2-3 GETメソッドの作成

  • com.example.demo にリポジトリインタフェースを作成します。
  • 継承元のJpaRepositoryはfind、save、delete、existsなど一般的にDB操作に必要なメソッドを一通り持っています。
TodoRepository.kt
package com.example.demo

import org.springframework.data.jpa.repository.JpaRepository
import org.springframework.stereotype.Repository

@Repository
interface TodoRepository : JpaRepository<Todo, Long>
  • com.example.demo に controllerクラスを作成します。
  • 作成したTodoRepositoryをインジェクションします。
TodoController.kt
package com.example.demo

import org.springframework.web.bind.annotation.GetMapping
import org.springframework.web.bind.annotation.RestController

@RestController
class TodoController(
        val todoRepository: TodoRepository

) {

    @GetMapping("/todos")
    fun getTodos(): List<Todo> {
        return todoRepository.findAll()
    }
}
  • demoアプリケーションを起動して、 http://localhost:8080/todos にアクセスすると、以下のように出ればOKです。

image.png

おわり

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?