SpringBoot, Kotlin, Mysql사용해서 Rest-Api 만들기

겜돌이곰이아부지·2023년 3월 23일
0

SpringBoot

목록 보기
1/1

SpringBoot, Kotlin, Mysql사용해서 Rest-Api 만들기

이번에는 Spring boot, Kotlin언어와 데이터베이스는 Mysql을 사용해서
Rest-Api를 만들어 볼까합니다.
DB설계는 간단하게 할꺼고, 목적은 Back-end Rest-Api구조를 만드는것이 목적입니다.

:sunny: 프로젝트 환경

  • Springboot 3.0.4 (글 작성 현재 기준 최신)

  • Kotlin 1.7.22

  • Mysql 8.0.31

  • Jvm17

:sunny: 프로젝트 생성

IntellijIdea 를 기준으로 하겠습니다.

![스크린샷 2023-03-18 오전 3.06.43](images/스크린샷 2023-03-18 오전 3.06.43.png)

![스크린샷 2023-03-18 오전 3.07.01](images/스크린샷 2023-03-18 오전 3.07.01.png)

Dependency는 Spring Boot DevTools, Spring Web만 선택하고 Create를 눌러 줍니다.

Mysql관련 설정은 수동으로 하도록 하겠습니다.

프로젝트 생성후 실행

생성된 프로젝트를 실행후 localhost:8080을 접속해서 아래이미지 처럼 나오면 일단 성공이다.

![스크린샷 2023-03-18 오전 4.43.23](images/스크린샷 2023-03-18 오전 4.43.23.png)

:sunny: Application 설정

  • resource/application.property -> yml로 이름 변경 (저는 yml파일이 편하더라구요)

  • 저는 기본포트말고 9999으로 포트 변경 해주었습니다.

  • rest-api prefix path를 셋팅해주었습니다. /api/v1

spring:
  profiles:
    active: local

  application:
    name: toyProject

  jpa:
    database: mysql
    database-platform: org.hibernate.dialect.MySQLDialect
    #    properties.hibernate.show_sql: true
    properties:
      hibernate:
        show_sql: true
        format_sql: true

server:
  port: 9999
  servlet:
    context-path: /api/v1/
  error:
    include-message: always

build.gradle.kts 에 추가 설정

kotlin("plugin.jpa") version "1.7.22" //JPA를 사용하기 위한 플러그인
kotlin("plugin.allopen") version "1.7.22" //Kotlin Open으로 만들어주는 플러그인이나 모두 열어주지 않음
kotlin("plugin.noarg") version "1.7.22"
kotlin("kapt") version "1.7.22" // Java Annotation 처리

위의 kotlin("plugin.noarg") 이 하는일

@Entity, @Embeddable, @MappedSuperClass 어노테이션이 붙은 클래스에 자동으로 기본 생성자를 만들어줌

덕분에 Hibernate의 Reflection을 사용 할 수 있게된다.

Dependency 추가

  • Mysql
implementation("org.springframework.boot:spring-boot-starter-data-jpa")
runtimeOnly("mysql:mysql-connector-java:8.0.32")

:sunny: Controller 만들기

테스트할 controller를 만든다

저는 그냥 테스트 목적으로 ToyController라는 이름으로 만드겠습니다.

package com.example.toyproject

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

@RestController
@RequestMapping("/test")
class ToyController {

    @GetMapping
    fun stringPrint(): String {
        return "toyProject"
    }
}
  • localhost:9999/api/v1/test로 접속해보면 toyProject가 출력 됩니다.(참고로 저는 포트를 9999로 변경했습니다.)

​ 포트변경은 위의 application.yml을 참고 하시면 되겠습니다.

:sunny: Mysql 데이터 조회

DB 생성하는 부분은 생략하고 기존에 들어가 있는 데이터를 조회해 보겠습니다.

저 같은 경우 판매자 정보를 조회하는 DTO를 만들어 보겠습니다.

ToyService, ToyRepository을 만들겠습니다.

// ToyService.kt
package com.example.toyproject

import org.springframework.stereotype.Service

@Service
class ToyService(
    private val toyRepository: ToyRepository
) {
    fun getSeller(
        sellerIds: List<Long>
    ):List<Seller> {
        return toyRepository.findAllById(sellerIds)
    }
}
// ToyRepository.kt
package com.example.toyproject

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

interface ToyRepository: JpaRepository<Seller, Long>

위에 사용된 Seller Entity도 간단히 만들겠습니다.

// Seller (Entity)
package com.example.toyproject

import com.fasterxml.jackson.annotation.JsonIgnore
import jakarta.persistence.*
import org.hibernate.annotations.BatchSize
import java.time.LocalDateTime

@Entity
class Seller(
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    val id: Long,
    val email: String,
    @JsonIgnore
    var password: String,
    val isAgreeToMarketing: Boolean,
    var phone: String,
    var isGoodbye: Boolean,
    val createdAt: LocalDateTime,
)

이제 DB에서 가져온 데이터를 최종 리턴할 DTO SellerRes 클래스를 만들겠습니다

// SellerRes.kt
package com.example.toyproject

import com.fasterxml.jackson.databind.PropertyNamingStrategies
import com.fasterxml.jackson.databind.annotation.JsonNaming
import java.time.LocalDateTime

@JsonNaming(PropertyNamingStrategies.SnakeCaseStrategy::class)
class SellerRes (
    val id: Long,
    val email: String,
    val isAgreeToMarketing: Boolean,
    val phone: String,
    var isGoodbye: Boolean,
    val createdAt: LocalDateTime
)

List로 가져온 Seller 데이터를 SellerRes에 맞게끔 변환해 줄 ToyTranslator클래스를 만듭니다.

// ToyTranslator.kt
package com.example.toyproject

object ToyTranslator {
    fun toSellerRes(
        seller: Seller
    ) = SellerRes(
        id = seller.id,
        email = seller.email,
        isAgreeToMarketing= seller.isAgreeToMarketing,
        phone = seller.phone,
        isGoodbye = seller.isGoodbye,
        createdAt = seller.createdAt
    )
}

이제 클래스를 다 만들었으니 프로젝트를 실행해서 Postman으로 데이터를 확인 해보겠습니다.

![스크린샷 2023-03-23 오전 5.02.04](images/스크린샷 2023-03-23 오전 5.02.04.png)

데이터가 잘 나오고 있습니다.

오늘은 Spring boot에서 Kotlin으로 간단한 RestApi를 만들어 보았습니다.

0개의 댓글