Development/Spring Boot3 (Kotlin)

[Kotlin][SpringBoot3] Kopring 서버 기본 실습 05 - MongoDB 연동하기 (MongoDB 7 사용)

Tradgineer 2023. 9. 7. 16:12

 

1. 이전 포스팅

 

https://growingsaja.tistory.com/964

 

 

 

 

 

2. mongodb 설치

 

필자의 경우 mac에서 진행하고 있으므로 아래 글을 참조해 진행했습니다.

 

https://growingsaja.tistory.com/966

 

 

 

 

 

3. 의존성 dependencyies 설정 추가

 

mongodb 의존성 추가

 

// vim build.gradle.kts



// ...



dependencies {



    // ...



    // mongodb
    implementation("org.springframework.boot:spring-boot-starter-data-mongodb")
}

    
    
// ...

 

 

 

 

 

4. application.properties 파일 수정해 연결 DB 설정 입력

 

 H2 database 설정 유지한채로 mongodb쪽 설정 추가

 

# vim application.properties

# db h2
spring.datasource.driver-class-name=org.h2.Driver
spring.datasource.url=jdbc:h2:mem:crypto-labs

# mongodb
spring.data.mongodb.uri=mongodb://localhost:27017/test

 

 

 

 

 

5. entity 파일 생성 및 소스코드 작성

 

// vim entities/User.kt

package com.example.practicekopring.entities

import org.springframework.data.annotation.Id
import org.springframework.data.mongodb.core.mapping.Document

@Document(collection = "users")
data class User(
    @Id
    val id: String? = null,
    val username: String,
    val email: String
)

 

 

 

 

 

 

 

 

6. repository 파일 생성 및 소스코드 작성

 

// vim repositories/UserRepository.kt

package com.example.practicekopring.repositories

import com.example.practicekopring.entities.User
import org.springframework.data.repository.CrudRepository

interface UserRepository : CrudRepository<User, String> {
    fun findByUsername(username: String): User?
}

 

 

 

 

 

7. service 파일 생성 및 소스코드 작성

 

// vim services/UserService.kt

package com.example.practicekopring.services

import com.example.practicekopring.entities.User
import com.example.practicekopring.repositories.UserRepository
import org.springframework.stereotype.Service

@Service
class UserService(private val userRepository: UserRepository) {

    fun createUser(username: String, email: String): User {
        val user = User(username = username, email = email)
        return userRepository.save(user)
    }

    fun getUserByUsername(username: String): User? {
        return userRepository.findByUsername(username)
    }
}

 

 

 

 

 

8. controller 파일 생성 및 소스코드 작성

 

// vim controllers/UserController.kt

package com.example.practicekopring.controllers

import com.example.practicekopring.entities.User
import com.example.practicekopring.services.UserService
import org.springframework.web.bind.annotation.GetMapping
import org.springframework.web.bind.annotation.PostMapping
import org.springframework.web.bind.annotation.RequestMapping
import org.springframework.web.bind.annotation.RequestParam
import org.springframework.web.bind.annotation.RestController
import org.springframework.web.bind.annotation.PathVariable

@RestController
@RequestMapping("/api/users")
class UserController(private val userService: UserService) {

    @PostMapping("/create")
    fun createUser(@RequestParam username: String, @RequestParam email: String): User {
        return userService.createUser(username, email)
    }

    @GetMapping("/{username}")
    fun getUserByUsername(@PathVariable username: String): User? {
        return userService.getUserByUsername(username)
    }
}

 

 

 

 

 

9. post method로 데이터 저장 및 조회 시도해서 정상 작동 확인

 

curl -X POST -H "Content-Type: application/x-www-form-urlencoded" -d 'username=testuser01&email=testuser01@gmail.com' http://localhost:8080/api/users/create

curl -X GET -H "Content-Type: application/json" http://localhost:8080/api/users/testuser01

 

 - 전

 

 - 후

 

 

 

 

 

10. 여러번 진행해보며 데이터 저장 기능 정상 작동 확인

 

curl -X POST -H "Content-Type: application/x-www-form-urlencoded" -d 'username=testuserSecond&email=testuser02@gmail.com' http://localhost:8080/api/users/create
# {"id":"64f59476f3dc171b96a450aa","username":"testuserSecond","email":"testuser02@gmail.com"}%

curl -X POST -H "Content-Type: application/x-www-form-urlencoded" -d 'username=testuserThird&email=testuser03@gmail.com' http://localhost:8080/api/users/create
# {"id":"64f59483f3dc171b96a450ab","username":"testuserThird","email":"testuser03@gmail.com"}%

curl -X POST -H "Content-Type: application/x-www-form-urlencoded" -d 'username=testuserHigh&email=testuser99@gmail.com' http://localhost:8080/api/users/create
# {"id":"64f59496f3dc171b96a450ac","username":"testuserHigh","email":"testuser99@gmail.com"}%

curl -X GET -H "Content-Type: application/json" http://localhost:8080/api/users/testuserSecond
# {"id":"64f59476f3dc171b96a450aa","username":"testuserSecond","email":"testuser02@gmail.com"}%

curl -X GET -H "Content-Type: application/json" http://localhost:8080/api/users/testuserThird
# {"id":"64f59483f3dc171b96a450ab","username":"testuserThird","email":"testuser03@gmail.com"}%

curl -X GET -H "Content-Type: application/json" http://localhost:8080/api/users/testuserHigh
# {"id":"64f59496f3dc171b96a450ac","username":"testuserHigh","email":"testuser99@gmail.com"}%