스프링 코틀린

김동혁·2023년 10월 22일

코틀린 스프링

목록 보기
1/1


스프링 코틀린 CR_UD


1. 개요:

주요 기능은 사용자 프로필(UserProfile)의 CRUD(Create, Read, Update, Delete) 작업을 수행하는 것입니다.


2. 코드 설명:

2.1. UserProfile 데이터 클래스:

  • @Entity: JPA(Entity Framework의 Kotlin 버전)에서 데이터베이스 테이블과 매핑되는 클래스임을 나타냅니다.
  • @Id @GeneratedValue: 데이터베이스에서 자동으로 생성되는 ID값임을 나타냅니다.
@Entity
data class UserProfile(
    @Id @GeneratedValue
    val id: Long? = null,
    val name: String,
    val email: String
)

2.2. UserProfileController 컨트롤러:

  • @RestController: 이 클래스가 RESTful 웹 서비스의 컨트롤러임을 나타냅니다.
  • @RequestMapping("/userProfiles"): 이 컨트롤러의 기본 URL 경로를 설정합니다.
package com.aloha.hello
import org.springframework.web.bind.annotation.*

@RestController
@RequestMapping("/userProfiles")  // URL 경로도 변경할 수 있습니다.
class UserProfileController(private val userProfileRepository: UserProfileRepository) {

    @GetMapping("/")
    fun getUsers() = userProfileRepository.findAll()

    @PostMapping("/")
    fun createUser(@RequestBody userProfile: UserProfile) = userProfileRepository.save(userProfile)

    @PutMapping("/{id}")
    fun updateUser(@PathVariable id: Long, @RequestBody userProfile: UserProfile) {
        val existingUser = userProfileRepository.findById(id).orElseThrow { Exception("User not found") }
        val updatedUser = existingUser.copy(name = userProfile.name, email = userProfile.email)
        userProfileRepository.save(updatedUser)
    }

    @DeleteMapping("/{id}")
    fun deleteUser(@PathVariable id: Long) = userProfileRepository.deleteById(id)
}

메서드별 설명:

  • getUsers(): 모든 사용자 프로필을 검색하여 반환합니다.
  • createUser(): 새로운 사용자 프로필을 데이터베이스에 저장합니다.
  • updateUser(): 특정 ID를 가진 사용자 프로필의 정보를 업데이트합니다.
  • deleteUser(): 특정 ID를 가진 사용자 프로필을 데이터베이스에서 삭제합니다.

2.3. UserProfileRepository 인터페이스:

  • JpaRepository 인터페이스를 확장하여 CRUD 작업을 위한 기본 메서드를 제공받습니다.
interface UserProfileRepository : JpaRepository<UserProfile, Long>

3. 요약:

이 코드는 Kotlin과 Spring Boot를 사용하여 사용자 프로필에 대한 CRUD 작업을 수행하는 웹 서비스를 생성하는 것입니다. 데이터베이스 연동은 JPA를 통해 이루어집니다.

H2 데이터베이스 설정:

spring.datasource.url: jdbc:h2:file:/Users/kimdonghyuk/spring/hello/testdb
spring.datasource.driverClassName: org.h2.Driver
spring.datasource.username & spring.datasource.password: sa & password
JPA(Hibernate) 설정:

spring.jpa.database-platform: org.hibernate.dialect.H2Dialect
spring.jpa.hibernate.ddl-auto: update
H2 데이터베이스 콘솔 설정:

spring.h2.console.enabled: true (H2 웹 콘솔 사용 가능)

profile
🐱 도쿄에서 활동 중인 웹 개발자 🇯🇵💻 🧑‍💻 최근에는 요즘IT에서 작가로도 활동 중입니다! 📝 요즘IT 글 모음: https://yozm.wishket.com/magazine/@donghyuk65/

0개의 댓글