본문 바로가기
개발 이야기/Springboot

[Kotlin] Springboot + Mybatis 사용법

by 농개 2020. 3. 28.
반응형

ORM 기술인 JPA를 사용해서 DB 데이터 조작, 조회를 하면 편하지만 때론 SQL만으로 쿼리를 짜서 조회할 상황도 있을 것이라 생각됩니다. 

 

MySQP + JPA 셋팅 방법은 여기 있습니다. https://basketdeveloper.tistory.com/74

 

[Kotlin] Spring boot에서 MySQL + JPA 사용법

지난번 Springboot + gradle 설정(https://basketdeveloper.tistory.com/73)에 이어 Spring boot에서 DB(Mysql) 간단 연동법과 JPA를 사용하는 방법을 정리해봅니다. 01. build.gradle.kt 에 Dependency 추가 impo..

basketdeveloper.tistory.com

이번에는 Kotlin +Spring boot 프로젝트 시 Mybatis 환경 셋팅에 대해서 정리합니다.

 

 

 

01. build.gradle.kts 에 mybatis 라이브러리 추가

...(중략)
repositories {
	mavenCentral()
}

dependencies {
	implementation("org.springframework.boot:spring-boot-starter-web")
	
	implementation("com.fasterxml.jackson.module:jackson-module-kotlin")
	implementation("org.jetbrains.kotlin:kotlin-reflect")
	implementation("org.jetbrains.kotlin:kotlin-stdlib-jdk8")
	
    	implementation("org.springframework.boot:spring-boot-starter-jdbc") // DB연결을 위한 JDBC
	implementation("mysql:mysql-connector-java") 			// Mysql Connector
	implementation("org.mybatis.spring.boot:mybatis-spring-boot-starter:1.3.2") // Mybatis

	testImplementation("org.springframework.boot:spring-boot-starter-test") {
		exclude(group = "org.junit.vintage", module = "junit-vintage-engine")
	}

}
...(중략)

관련 라이브러리 Gradle 파일에 추가해줍니다.

 

 

02. application.properties에 DB 연결정보 작성

server.address=localhost
server.port=8080

spring.datasource.jdbc-url=jdbc:mysql://127.0.0.1:3306/mydb
spring.datasource.username=dbuser
spring.datasource.password=password
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver

실제 연결할 호스트/포트/유저정보로 작성해주면 됩니다.

 

 

03. Spring Data Resource Config 작성

Spring boot 설정 파일을 하나 작성해줍니다.

package com.example.demo.spring

import com.zaxxer.hikari.HikariDataSource
import org.apache.ibatis.session.SqlSessionFactory
import org.mybatis.spring.SqlSessionFactoryBean
import org.mybatis.spring.annotation.MapperScan
import org.mybatis.spring.boot.autoconfigure.SpringBootVFS
import org.springframework.boot.context.properties.ConfigurationProperties
import org.springframework.boot.jdbc.DataSourceBuilder
import org.springframework.context.annotation.Bean
import org.springframework.context.annotation.Configuration
import org.springframework.context.annotation.Primary
import org.springframework.core.io.support.PathMatchingResourcePatternResolver
import javax.sql.DataSource

@Configuration
@MapperScan(
        basePackages = ["com.example.demo.api.**.repository"],
        sqlSessionFactoryRef = "sessionFactory"
)
class DataSourceConfig {
    @Primary
    @Bean
    @ConfigurationProperties("spring.datasource")
    fun dataSource(): DataSource {
        val dataSource = DataSourceBuilder.create().type(HikariDataSource::class.java).build()

        // UTF-8이 아닌 레거시 데이터베이스에 연결시 한글 문자열을 온전히 처리하기 위해 사용
        dataSource.connectionInitSql = "SET NAMES utf8mb4"

        return dataSource
    }

    @Primary
    @Bean
    fun sessionFactory(): SqlSessionFactory {
        val sqlSessionFactoryBean = SqlSessionFactoryBean()

        sqlSessionFactoryBean.setDataSource((this.dataSource()))
        sqlSessionFactoryBean.setTypeAliasesPackage("com.example.demo.api")
        sqlSessionFactoryBean.setMapperLocations(PathMatchingResourcePatternResolver().getResources("classpath:/mybatis/mapper/**/*.xml"))
        sqlSessionFactoryBean.vfs = SpringBootVFS::class.java

        return sqlSessionFactoryBean.`object`!!
    }
}

위와 같이 디비 연결을 위한 설정을 해주었습니다.

@Configuration 어노테이션을 통해 설정파일로 어플리케이션 실행시 읽어 드립니다.

@MapperScan 어노테이션으로 입력된 패키지기준으로 자동 스캔합니다. 그리고 SqlSessionFactory를 사용할 것이기에 Bean이름을 설정해줬습니다.

 

dataSource를 작성해주고

sessionsFactory 작성해줍니다.

/mybatis/mapper/**/*.xml 와 같이 설정해줬는데

resources 폴더(application.properties가 있는 폴더)내에 Mybatis SQL맵 파일을 작성할 것이기 때문입니다.

 

** Mybatis는 SqlSessionFactory을 통해 SqlSession을 생성합니다.

최종적으로 SqlSession에서 맵핑된 xml파일의 쿼리를 찾아 실행합니다.

 

 

04. SQL 작성

아래와 같이 resources/mybatis/mapper/member/member.xml 을 작성해줬습니다.

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.example.demo.api.member.repository.MemberSqlMapper">
    <select id="selectMemberCnt" resultType="int">
        SELECT count(*)
        FROM MEMBER
    </select>
</mapper>

간단히 member 테이블 카운트 조회 쿼리입니다. resultType은 int로 했습니다.

 

 

05. Repository 작성

package com.example.demo.api.member.repository

import org.apache.ibatis.annotations.Mapper
import org.springframework.stereotype.Repository

@Repository
@Mapper
interface MemberSqlMapper {
    fun selectMemberCnt() : Int
}

위와 같이 맵퍼파일의 id와 일치하게 메서드를 작성해줬습니다.

끝입니다. 이제 서비스단에서 호출해서 사용하기만 하면됩니다.

 

 

06. 사용

@RestController
@RequestMapping("/members")
class MemberController(
        val memberSqlMapper: MemberSqlMapper
) {
    @GetMapping()
    fun getMemberList(@RequestParam type: String?): ResponseEntity<*> {
        
        val userCnt = memberSqlMapper.getMemberCnt() // 유저 카운트 조회

        val data = HashMap<String, Any>()
        data["userCnt"] = userCnt
        
        return ResponseEntity.ok(data)
    }
}

위는 예시구요. Spring 경험이 있으신 분들은 Service 단에서 저런식으로 호출하여 사용하면 될 것입니다.

 

반응형