[kotlin] 코틀린과 JPA를 이용한 데이터베이스 연동

본 포스트에서는 코틀린 언어를 사용하여 JPA(Java Persistence API)를 이용하여 데이터베이스와의 연동을 다룰 것입니다. JPA는 자바에서 데이터베이스를 다루기 위한 API로, 코틀린 언어와의 연동이 원활하게 될 수 있습니다.

JPA 설정

JPA와 데이터베이스를 연동하기 위해, 먼저 프로젝트의 pom.xml 파일에 Maven 또는 Gradle 디펜던시를 추가해야 합니다.

Maven 설정

<dependencies>
    <!-- JPA -->
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-data-jpa</artifactId>
    </dependency>
    
    <!-- 데이터베이스 드라이버 -->
    <dependency>
        <groupId>com.h2database</groupId>
        <artifactId>h2</artifactId>
        <scope>runtime</scope>
    </dependency>
</dependencies>

Gradle 설정

dependencies {
    // JPA
    implementation 'org.springframework.boot:spring-boot-starter-data-jpa'
    
    // 데이터베이스 드라이버
    runtimeOnly 'com.h2database:h2'
}

엔티티 클래스 생성

다음으로는 JPA가 인식할 수 있는 엔티티 클래스를 정의해야 합니다. 이 클래스를 통해 데이터베이스 테이블과 매핑됩니다.

import javax.persistence.Entity
import javax.persistence.Id

@Entity
data class Product(
    @Id
    val id: Long,
    val name: String,
    val price: Double
)

여기서 @Entity 어노테이션은 해당 클래스가 엔티티임을 JPA에게 알려주며, @Id 어노테이션은 해당 필드가 엔티티의 기본 키(primary key)임을 나타냅니다.

레포지토리 인터페이스 생성

다음으로는 JPA 레포지토리를 위한 인터페이스를 생성해야 합니다. 이 인터페이스를 통해 데이터베이스 조작이 가능해집니다.

import org.springframework.data.repository.CrudRepository

interface ProductRepository : CrudRepository<Product, Long>

위의 코드에서 ProductRepositoryCrudRepository 인터페이스를 상속받았으며, Product 엔티티와 기본 키의 타입(여기서는 Long)을 제공함으로써 기본적인 CRUD(create, read, update, delete) 기능을 제공합니다.

데이터베이스 연동 테스트

이제 코틀린과 JPA를 이용하여 데이터베이스가 잘 연동되었는지 테스트해보겠습니다.

import org.springframework.beans.factory.annotation.Autowired
import org.springframework.boot.CommandLineRunner
import org.springframework.stereotype.Component

@Component
class DatabaseTester @Autowired constructor(
    private val productRepository: ProductRepository
) : CommandLineRunner {

    override fun run(vararg args: String?) {
        val product = Product(1, "Example Product", 9.99)
        productRepository.save(product)

        val retrievedProduct = productRepository.findById(1)
        println(retrievedProduct)
    }
}

위의 코드에서 CommandLineRunner를 구현한 DatabaseTester 클래스는 애플리케이션 실행 시점에 자동으로 실행되며, Product 엔티티를 생성하고 이를 데이터베이스에 저장한 후, 다시 읽어오는 과정을 보여줍니다.

마치며

위의 과정을 통해 코틀린 언어를 사용하여 JPA를 이용한 데이터베이스 연동을 구현해 보았습니다. 이를 통해 코틀린으로 개발하는 프로젝트에서도 JPA를 통해 데이터베이스를 쉽게 다룰 수 있음을 알 수 있습니다.

참고문헌: