티스토리 뷰

728x90
// build.gradle.kts
plugins {
    id("org.springframework.boot") version "3.2.0"
    id("io.spring.dependency-management") version "1.1.4"
    kotlin("jvm") version "1.9.20"
    kotlin("plugin.spring") version "1.9.20"
    kotlin("plugin.jpa") version "1.9.20"
}

group = "com.example"
version = "0.0.1-SNAPSHOT"

repositories {
    mavenCentral()
}

dependencies {
    implementation("org.springframework.boot:spring-boot-starter-web")
    implementation("org.springframework.boot:spring-boot-starter-data-jpa")
    implementation("com.fasterxml.jackson.module:jackson-module-kotlin")
    implementation("org.jetbrains.kotlin:kotlin-reflect")
    runtimeOnly("com.h2database:h2")
    testImplementation("org.springframework.boot:spring-boot-starter-test")
}

 

// src/main/kotlin/com/example/demo/Application.kt
package com.example.demo

import org.springframework.boot.autoconfigure.SpringBootApplication
import org.springframework.boot.runApplication

@SpringBootApplication
class Application

fun main(args: Array<String>) {
    runApplication<Application>(*args)
}

 

// src/main/kotlin/com/example/demo/model/User.kt
package com.example.demo.model

import jakarta.persistence.Entity
import jakarta.persistence.GeneratedValue
import jakarta.persistence.GenerationType
import jakarta.persistence.Id
import jakarta.persistence.Table

@Entity
@Table(name = "users")
data class User(
    @Id @GeneratedValue(strategy = GenerationType.IDENTITY)
    val id: Long = 0,
    val name: String,
    val email: String,
    val age: Int
)

 

// src/main/kotlin/com/example/demo/repository/UserRepository.kt
package com.example.demo.repository

import com.example.demo.model.User
import org.springframework.data.jpa.repository.JpaRepository
import org.springframework.stereotype.Repository

@Repository
interface UserRepository : JpaRepository<User, Long> {
    fun findByEmail(email: String): User?
}

 

// src/main/kotlin/com/example/demo/dto/UserDto.kt
package com.example.demo.dto

data class UserCreateDto(
    val name: String,
    val email: String,
    val age: Int
)

data class UserResponseDto(
    val id: Long,
    val name: String,
    val email: String,
    val age: Int
)

 

// src/main/kotlin/com/example/demo/service/UserService.kt
package com.example.demo.service

import com.example.demo.dto.UserCreateDto
import com.example.demo.dto.UserResponseDto
import com.example.demo.model.User
import com.example.demo.repository.UserRepository
import org.springframework.stereotype.Service

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

    fun createUser(userDto: UserCreateDto): UserResponseDto {
        val user = User(
            name = userDto.name,
            email = userDto.email,
            age = userDto.age
        )
        val savedUser = userRepository.save(user)
        return UserResponseDto(
            id = savedUser.id,
            name = savedUser.name,
            email = savedUser.email,
            age = savedUser.age
        )
    }

    fun getAllUsers(): List<UserResponseDto> {
        return userRepository.findAll().map { user ->
            UserResponseDto(
                id = user.id,
                name = user.name,
                email = user.email,
                age = user.age
            )
        }
    }

    fun getUserById(id: Long): UserResponseDto? {
        val user = userRepository.findById(id).orElse(null) ?: return null
        return UserResponseDto(
            id = user.id,
            name = user.name,
            email = user.email,
            age = user.age
        )
    }

    fun updateUser(id: Long, userDto: UserCreateDto): UserResponseDto? {
        val existingUser = userRepository.findById(id).orElse(null) ?: return null
        
        val updatedUser = existingUser.copy(
            name = userDto.name,
            email = userDto.email,
            age = userDto.age
        )
        
        val savedUser = userRepository.save(updatedUser)
        return UserResponseDto(
            id = savedUser.id,
            name = savedUser.name,
            email = savedUser.email,
            age = savedUser.age
        )
    }

    fun deleteUser(id: Long): Boolean {
        if (!userRepository.existsById(id)) {
            return false
        }
        userRepository.deleteById(id)
        return true
    }
}

 

// src/main/kotlin/com/example/demo/controller/UserController.kt
package com.example.demo.controller

import com.example.demo.dto.UserCreateDto
import com.example.demo.dto.UserResponseDto
import com.example.demo.service.UserService
import org.springframework.http.HttpStatus
import org.springframework.http.ResponseEntity
import org.springframework.web.bind.annotation.*

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

    @PostMapping
    fun createUser(@RequestBody userDto: UserCreateDto): ResponseEntity<UserResponseDto> {
        val createdUser = userService.createUser(userDto)
        return ResponseEntity(createdUser, HttpStatus.CREATED)
    }

    @GetMapping
    fun getAllUsers(): ResponseEntity<List<UserResponseDto>> {
        val users = userService.getAllUsers()
        return ResponseEntity(users, HttpStatus.OK)
    }

    @GetMapping("/{id}")
    fun getUserById(@PathVariable id: Long): ResponseEntity<UserResponseDto> {
        val user = userService.getUserById(id)
        return if (user != null) {
            ResponseEntity(user, HttpStatus.OK)
        } else {
            ResponseEntity(HttpStatus.NOT_FOUND)
        }
    }

    @PutMapping("/{id}")
    fun updateUser(@PathVariable id: Long, @RequestBody userDto: UserCreateDto): ResponseEntity<UserResponseDto> {
        val updatedUser = userService.updateUser(id, userDto)
        return if (updatedUser != null) {
            ResponseEntity(updatedUser, HttpStatus.OK)
        } else {
            ResponseEntity(HttpStatus.NOT_FOUND)
        }
    }

    @DeleteMapping("/{id}")
    fun deleteUser(@PathVariable id: Long): ResponseEntity<Void> {
        return if (userService.deleteUser(id)) {
            ResponseEntity(HttpStatus.NO_CONTENT)
        } else {
            ResponseEntity(HttpStatus.NOT_FOUND)
        }
    }
}

 

// src/main/resources/application.yml
spring:
  datasource:
    url: jdbc:h2:mem:testdb
    driverClassName: org.h2.Driver
    username: sa
    password: password
  jpa:
    database-platform: org.hibernate.dialect.H2Dialect
    hibernate:
      ddl-auto: update
  h2:
    console:
      enabled: true
      path: /h2-console

 

https://docs.spring.io/spring-framework/reference/languages/kotlin.html

728x90
250x250
공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
TAG
more
«   2025/04   »
1 2 3 4 5
6 7 8 9 10 11 12
13 14 15 16 17 18 19
20 21 22 23 24 25 26
27 28 29 30
글 보관함