이번에는 Spring boot, Kotlin언어와 데이터베이스는 Mysql을 사용해서
Rest-Api를 만들어 볼까합니다.
DB설계는 간단하게 할꺼고, 목적은 Back-end Rest-Api구조를 만드는것이 목적입니다.
Springboot 3.0.4 (글 작성 현재 기준 최신)
Kotlin 1.7.22
Mysql 8.0.31
Jvm17
IntellijIdea 를 기준으로 하겠습니다.


Dependency는 Spring Boot DevTools, Spring Web만 선택하고 Create를 눌러 줍니다.
Mysql관련 설정은 수동으로 하도록 하겠습니다.
생성된 프로젝트를 실행후 localhost:8080을 접속해서 아래이미지 처럼 나오면 일단 성공이다.

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
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 처리
@Entity
, @Embeddable
, @MappedSuperClass
어노테이션이 붙은 클래스에 자동으로 기본 생성자를 만들어줌
덕분에 Hibernate의 Reflection을 사용 할 수 있게된다.
implementation("org.springframework.boot:spring-boot-starter-data-jpa")
runtimeOnly("mysql:mysql-connector-java:8.0.32")
테스트할 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"
}
}
포트변경은 위의 application.yml을 참고 하시면 되겠습니다.
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으로 데이터를 확인 해보겠습니다.

데이터가 잘 나오고 있습니다.
오늘은 Spring boot에서 Kotlin으로 간단한 RestApi를 만들어 보았습니다.