728x90

Java 로 된 Spring Batch 는 예제는 많지만 Kotlin 으로 된 예제는 부족한 것 같아 실전 프로젝트 처럼 예제를 작성 하기로 했습니다.


모든 code 는 아래 github 에서 확인해주세요

https://github.com/nothingprogram/spring-batch-practice

 

GitHub - nothingprogram/spring-batch-practice

Contribute to nothingprogram/spring-batch-practice development by creating an account on GitHub.

github.com

 

Project setup 하기

build.gradle.kts

 

import org.jetbrains.kotlin.gradle.tasks.KotlinCompile

plugins {
    id("org.springframework.boot") version "2.7.4"
    id("io.spring.dependency-management") version "1.0.14.RELEASE"
    kotlin("jvm") version "1.6.21"
    kotlin("plugin.spring") version "1.6.21"
    kotlin("plugin.jpa") version "1.6.21"
}

group = "그룹 이름 작성"
version = "0.0.1-SNAPSHOT"
java.sourceCompatibility = JavaVersion.VERSION_11

allOpen {
    annotation("javax.persistence.Entity")
    annotation("javax.persistence.Embeddable")
    annotation("javax.persistence.MappedSuperclass")
}

repositories {
    mavenCentral()
}

dependencies {
    implementation("org.springframework.boot:spring-boot-starter-batch")
    implementation("org.springframework.boot:spring-boot-starter-data-jpa")
    implementation("org.jetbrains.kotlin:kotlin-reflect")
    implementation("org.jetbrains.kotlin:kotlin-stdlib-jdk8")
    runtimeOnly("mysql:mysql-connector-java")
    testImplementation("org.springframework.boot:spring-boot-starter-test")
    testImplementation("org.springframework.batch:spring-batch-test")
}

tasks.withType<KotlinCompile> {
    kotlinOptions {
        freeCompilerArgs = listOf("-Xjsr305=strict")
        jvmTarget = "11"
    }
}

tasks.withType<Test> {
    useJUnitPlatform()
}

 

batch 를 사용하기 위해서 annotation 을 추가합니다.

@SpringBootApplication
@EnableBatchProcessing
class SpringBatchPracticeApplication

 

csv 파일을 읽어서 mysql 에 저장하는 Job 을 만들기

@Configuration
class FileJobConfiguration(
    private val jobBuilderFactory: JobBuilderFactory,
    private val stepBuilderFactory: StepBuilderFactory,
    private val entityManagerFactory: EntityManagerFactory
) {

    @Bean
    fun fileJob(): Job {
        return jobBuilderFactory.get("fileJob")
            .start(fileStep())
            .build()
    }

    @Bean
    fun fileStep(): Step {
        return stepBuilderFactory.get("fileStep")
            .chunk<ProductVO, Product>(10)
            .reader(fileItemReader(null))
            .processor(fileItemProcessor())
            .writer(fileItemWriter())
            .build()
    }

    @Bean
    @StepScope
    fun fileItemReader(
        @Value("#{jobParameters['requestDate']}")
        requestDate: String?
    ): FlatFileItemReader<ProductVO> {
        return FlatFileItemReaderBuilder<ProductVO>()
            .name("flatFile")
            .resource(ClassPathResource("product_${requestDate}.csv"))
            .fieldSetMapper { fieldSet ->
                ProductVO(
                    id = fieldSet.readLong("id"),
                    name = fieldSet.readString("name"),
                    price = fieldSet.readInt("price"),
                    type = fieldSet.readString("type")
                )
            }
            .linesToSkip(1)
            .delimited()
            .names("id", "name", "price", "type")
            .build()
    }

    @Bean
    fun fileItemProcessor(): ItemProcessor<ProductVO, Product> {
        return FileItemProcessor()
    }

    @Bean
    fun fileItemWriter(): ItemWriter<Product> {
        return JpaItemWriterBuilder<Product>()
            .entityManagerFactory(entityManagerFactory)
            .usePersist(true)
            .build()
    }

}

 

 

itemProcessor 로 converting 하기

class FileItemProcessor : ItemProcessor<ProductVO, Product> {
    override fun process(item: ProductVO): Product {
        return Product(
            id = item.id,
            name = item.name,
            price = item.price,
            type = item.type
        )
    }
}

 

 

requestDate 로 날짜를 넣어준뒤 실행하면 

 

 

mysql 에 잘들어간 것을 확인했습니다!

728x90