java 121 lines · 2 tabs

Batch processing with Spring Batch

David Kumar Jan 2026
2 tabs
package com.example.demo.batch;

import com.example.demo.model.User;
import com.example.demo.model.UserDTO;
import org.springframework.batch.core.Job;
import org.springframework.batch.core.Step;
import org.springframework.batch.core.job.builder.JobBuilder;
import org.springframework.batch.core.repository.JobRepository;
import org.springframework.batch.core.step.builder.StepBuilder;
import org.springframework.batch.item.ItemProcessor;
import org.springframework.batch.item.database.JdbcBatchItemWriter;
import org.springframework.batch.item.database.JdbcPagingItemReader;
import org.springframework.batch.item.database.builder.JdbcBatchItemWriterBuilder;
import org.springframework.batch.item.database.builder.JdbcPagingItemReaderBuilder;
import org.springframework.batch.item.file.FlatFileItemReader;
import org.springframework.batch.item.file.builder.FlatFileItemReaderBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.ClassPathResource;
import org.springframework.transaction.PlatformTransactionManager;

import javax.sql.DataSource;

@Configuration
public class BatchConfig {

    @Bean
    public Job userImportJob(JobRepository jobRepository, Step importStep) {
        return new JobBuilder("userImportJob", jobRepository)
            .start(importStep)
            .build();
    }

    @Bean
    public Step importStep(JobRepository jobRepository,
                          PlatformTransactionManager transactionManager,
                          FlatFileItemReader<UserDTO> reader,
                          UserProcessor processor,
                          JdbcBatchItemWriter<User> writer) {
        return new StepBuilder("importStep", jobRepository)
            .<UserDTO, User>chunk(100, transactionManager)
            .reader(reader)
            .processor(processor)
            .writer(writer)
            .faultTolerant()
            .skip(Exception.class)
            .skipLimit(10)
            .build();
    }

    @Bean
    public FlatFileItemReader<UserDTO> csvReader() {
        return new FlatFileItemReaderBuilder<UserDTO>()
            .name("userCsvReader")
            .resource(new ClassPathResource("users.csv"))
            .delimited()
            .names("name", "email", "age")
            .targetType(UserDTO.class)
            .linesToSkip(1)
            .build();
    }

    @Bean
    public UserProcessor processor() {
        return new UserProcessor();
    }

    @Bean
    public JdbcBatchItemWriter<User> databaseWriter(DataSource dataSource) {
        return new JdbcBatchItemWriterBuilder<User>()
            .dataSource(dataSource)
            .sql("INSERT INTO users (name, email, age) VALUES (:name, :email, :age)")
            .beanMapped()
            .build();
    }

    public static class UserProcessor implements ItemProcessor<UserDTO, User> {
        @Override
        public User process(UserDTO dto) throws Exception {
            if (dto.email() == null || !dto.email().contains("@")) {
                return null; // Skip invalid records
            }

            User user = new User();
            user.setName(dto.name().toUpperCase());
            user.setEmail(dto.email().toLowerCase());
            user.setAge(dto.age());
            return user;
        }
    }
}
2 files · java Explain with highlit

Spring Batch handles large-scale batch processing—ETL, data migration, report generation. Jobs contain steps; steps have readers, processors, and writers. Chunk-oriented processing reads, processes, and writes data in configurable batches. ItemReader fetches data from databases, files, or APIs. ItemProcessor transforms data. ItemWriter persists results. Skip and retry logic handles failures gracefully. Job parameters enable reusability. JobRepository tracks execution metadata. Partitioning parallelizes processing across threads or nodes. Listeners provide hooks for monitoring and logging. Spring Batch ensures fault tolerance and restartability. It's ideal for scheduled bulk operations, data synchronization, and business-critical batch workflows. Proper configuration balances memory usage, throughput, and reliability.


Related snips

graphql
type User {
    id: ID!
    name: String!
    email: String!
    posts: [Post!]!
    createdAt: String!

GraphQL API with Spring Boot

java graphql spring-boot
by David Kumar 3 tabs
typescript
export type Settled<R> =
  | { status: 'fulfilled'; value: R }
  | { status: 'rejected'; reason: unknown };

export interface ConcurrencyOptions {
  limit: number;

Simple concurrency limiter for batch operations

node concurrency async
by codesnips 2 tabs
java
package com.example.starter.config;

import com.example.starter.properties.CustomProperties;
import com.example.starter.service.CustomService;
import org.springframework.boot.autoconfigure.AutoConfiguration;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;

Custom Spring Boot starters

java spring-boot starter
by David Kumar 4 tabs
java
package com.example.demo.config;

import org.apache.kafka.clients.consumer.ConsumerConfig;
import org.apache.kafka.clients.producer.ProducerConfig;
import org.apache.kafka.common.serialization.StringDeserializer;
import org.apache.kafka.common.serialization.StringSerializer;

Messaging with Apache Kafka

java kafka messaging
by David Kumar 3 tabs
java
package com.example.demo.controller;

import com.example.demo.dto.FileMetadata;
import com.example.demo.service.FileStorageService;
import org.springframework.core.io.Resource;
import org.springframework.http.HttpHeaders;

File upload and download handling

java spring-boot file-upload
by David Kumar 2 tabs
sql
CREATE TABLE users (
    id BIGSERIAL PRIMARY KEY,
    username VARCHAR(100) NOT NULL UNIQUE,
    email VARCHAR(255) NOT NULL UNIQUE,
    password VARCHAR(255) NOT NULL,
    created_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,

Database migration with Flyway

java flyway database-migration
by David Kumar 6 tabs

Share this code

Here's the card — post it anywhere.

Batch processing with Spring Batch — share card
Link copied