[spring.io] 스프링 JDBC를 활용하여 관계형 데이터베이스 연동하기(코틀린 ver.)

#kotlin #spring

참고 사이트 : https://spring.io/guides/gs/relational-data-access/

스프링의 JdbcTemplate 을 사용하여 관계형 데이터베이스에 저장된 데이터에 접근하는 애플리케이션을 작성합니다.

Spring Initializr 로 시작하기

메이븐 기준으로 다음 의존성을 추가한 프로젝트를 생성합니다.

  • Spring DATA JDBC
  • H2 Database
<dependencies>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-data-jdbc</artifactId>
    </dependency>
    <dependency>
        <groupId>org.jetbrains.kotlin</groupId>
        <artifactId>kotlin-reflect</artifactId>
    </dependency>
    <dependency>
        <groupId>org.jetbrains.kotlin</groupId>
        <artifactId>kotlin-stdlib-jdk8</artifactId>
    </dependency>

    <dependency>
        <groupId>com.h2database</groupId>
        <artifactId>h2</artifactId>
        <scope>runtime</scope>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-test</artifactId>
        <scope>test</scope>
        <exclusions>
            <exclusion>
                <groupId>org.junit.vintage</groupId>
                <artifactId>junit-vintage-engine</artifactId>
            </exclusion>
        </exclusions>
    </dependency>
</dependencies>

Customer 객체 생성하기

간단한 데이터 접근 로직 테스트를 위해서 서비스에서 사용할 Customer 클래스를 생성합니다.

class Customer(
        val id : Long,
        val firstName : String,
        val lastName : String
) {
    override fun toString(): String {
        return “Customer id=$id, firstName=‘$firstName’, lastName=‘$lastName’]”
    }
}

JDBC 로 H2 데이터 데이터 베이스에 SQL 쿼리 실행하기

생성자에서 JdbcTemplate 객체를 주입받아 사용합니다.
Customer 리스트를 생성한 후 jdbcTemplate.batchUpdate 로 데이터베이스에 적재합니다.
적재 이후에는 SELECT 쿼리를 사용하여 전체 Customer 목록을 조회한 후 log로 출력합니다.

@SpringBootApplication
class JdbcApplication(
        val jdbcTemplate: JdbcTemplate
): CommandLineRunner{

    override fun run(vararg args: String?) {
        val log = LoggerFactory.getLogger(this.javaClass)

        log.info("Creating tables");

        jdbcTemplate.execute("DROP TABLE customers IF EXISTS");
        jdbcTemplate.execute("CREATE TABLE customers(" + "id SERIAL, first_name VARCHAR(255), last_name VARCHAR(255))");

        val splitUpNames = listOf<String>("John Woo", "Jeff Dean", "Josh Bloch", "Josh Long")
                .map{ it.split(" ").toTypedArray()}


        splitUpNames.forEach { log.info("Inserting customer record for ${it[0]} / ${it[1]}") }

        jdbcTemplate.batchUpdate("INSERT INTO customers(first_name, last_name) VALUES (?,?)", splitUpNames);

        log.info("Querying for customer records where first_name = 'Josh':");

        jdbcTemplate.query("SELECT id, first_name, last_name FROM customers") {
            rs, rowNum -> println("${rs.getLong("id")}, ${rs.getString("first_name")}, ${rs.getString("last_name")} $rowNum")
        }
    }
}

출력 결과

1, John, Woo 0
2, Jeff, Dean 1
3, Josh, Bloch 2
4, Josh, Long 3

다른 카테고리의 글 목록

Spring 카테고리의 포스트를 톺아봅니다