0Pricing
Spring Boot 4 Complete Guide · บทเรียน

งาน ขั้นตอน และโมเดล JobRepository

จัดโครงสร้างเวิร์กโหลดแบบแบตช์ด้วยงาน ขั้นตอน และการคงอยู่ของข้อมูลเมตาเพื่อติดตามการทำงาน

งาน ขั้นตอน และโมเดล JobRepository เป็นบทเรียน Spring Boot 4 Complete Guide ฟรีบน CoddyKit นี่คือบทเรียนที่ 1 จากทั้งหมด 4 บทเรียน คุณสามารถอ่านบทเรียนทั้งหมดด้านล่างฟรี — จากนั้นลองปฏิบัติด้วยตัวคุณเองในเบราว์เซอร์พร้อมตัวแก้ไขโค้ดในตัวและติวเตอร์ AI ตลอด 24/7 บทเรียนนี้เป็นส่วนหนึ่งของเส้นทางการเรียน Spring Boot 4 Complete Guide และความก้าวหน้าของคุณจะซิงค์ข้ามเว็บและแอป CoddyKit คอร์ส Spring Boot 4 Complete Guide มีบทเรียนทั้งหมด 4 บทเรียน

บางส่วนของบทเรียนนี้ยังไม่ได้รับการแปล และแสดงเป็นภาษาอังกฤษ

Why Spring Batch Exists

Many real-world workloads are not request/response: nightly invoice generation, CSV imports, report exports, data migrations. These run as batch jobs processing large volumes of records.

  • They must be restartable after a crash.
  • They must track progress so you know what already ran.
  • They must handle millions of rows without loading everything into memory.

Spring Batch gives you a structured model for exactly this. The three core abstractions you must understand first are the Job, the Step, and the JobRepository.

The Job: A Unit of Work

A Job is the top-level container for an entire batch process. It has a name and is composed of one or more ordered Step instances.

  • One Job definition can be executed many times — each run is a JobInstance.
  • Each attempt at running a JobInstance is a JobExecution (status, start time, exit code).

In Spring Boot 4 you build a Job with a JobBuilder, supplying a name and a JobRepository.

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

JobInstance vs JobExecution

This distinction is the heart of restartability. Suppose you run importInvoicesJob for the date 2026-06-10.

  • The JobInstance is identified by the job name plus its identifying job parameters (here, the date). Re-running with the same date refers to the same instance.
  • Each run produces a new JobExecution. If the first attempt fails and you restart, you get a second JobExecution for the same JobInstance.

A completed JobInstance cannot be run again with the same identifying parameters — Spring Batch throws JobInstanceAlreadyCompleteException. This prevents accidental double-processing.

The Step: A Phase of the Job

A Step is an independent, sequential phase of a Job. A Job typically chains several steps: validate input, then process records, then send a summary email.

There are two flavors of step:

  • Chunk-oriented: read–process–write in configurable chunks. Ideal for large data sets.
  • Tasklet: a single arbitrary action (delete a file, run a stored procedure, ping a service).

Each Step run is tracked by a StepExecution, which records read/write counts, commit count, and status.

A Chunk-Oriented Step

A chunk-oriented step ties together an ItemReader, an optional ItemProcessor, and an ItemWriter. The chunk(n, transactionManager) call sets the commit interval: after every n items are read and processed, the writer flushes and the transaction commits.

Smaller chunks mean more frequent commits (safer restart point, more overhead); larger chunks mean fewer commits (faster, but more work lost on rollback).

@Bean
public Step readStep(JobRepository jobRepository,
                     PlatformTransactionManager txManager,
                     ItemReader<Invoice> reader,
                     ItemProcessor<Invoice, Invoice> processor,
                     ItemWriter<Invoice> writer) {
    return new StepBuilder("readStep", jobRepository)
            .<Invoice, Invoice>chunk(100, txManager)
            .reader(reader)
            .processor(processor)
            .writer(writer)
            .build();
}

A Tasklet Step

When a phase is a single action rather than a stream of items, use a Tasklet. The execute method returns RepeatStatus.FINISHED when done, or CONTINUABLE to be called again.

Tasklets are perfect for setup/cleanup steps such as archiving a processed file or truncating a staging table.

@Bean
public Step cleanupStep(JobRepository jobRepository,
                        PlatformTransactionManager txManager) {
    return new StepBuilder("cleanupStep", jobRepository)
            .tasklet((contribution, chunkContext) -> {
                Path staging = Path.of("/data/staging.csv");
                Files.deleteIfExists(staging);
                return RepeatStatus.FINISHED;
            }, txManager)
            .build();
}

Composing Steps Into a Job

Steps run in the order you declare them. Use start(...) for the first step and next(...) to chain the rest. By default, the Job stops if a Step ends with status FAILED.

Here the job validates, imports, then cleans up. If the import step fails, cleanupStep does not run, and on restart the job resumes from the failed step.

@Bean
public Job invoiceJob(JobRepository jobRepository,
                      Step validateStep, Step readStep, Step cleanupStep) {
    return new JobBuilder("invoiceJob", jobRepository)
            .start(validateStep)
            .next(readStep)
            .next(cleanupStep)
            .build();
}

The JobRepository: Persistent Memory

The JobRepository is the component that persists all batch metadata: which JobInstances exist, their JobExecutions, each StepExecution, and the execution contexts.

  • It is how Spring Batch knows a job already completed.
  • It is how a restart figures out where to resume.
  • It stores read/write/commit counts for monitoring.

By default it writes to a relational database using a set of BATCH_* tables. Without a working JobRepository there is no restartability and no execution history — it is not optional.

The BATCH_ Metadata Tables

The JobRepository persists into a fixed schema. The key tables are:

  • BATCH_JOB_INSTANCE — one row per JobInstance (name + identity hash).
  • BATCH_JOB_EXECUTION — one row per run attempt, with status and exit code.
  • BATCH_STEP_EXECUTION — per-step counters (read/write/skip counts).
  • BATCH_JOB_EXECUTION_CONTEXT / BATCH_STEP_EXECUTION_CONTEXT — serialized state used to resume.
  • BATCH_*_SEQ — sequences for primary keys.

Spring Boot ships the DDL and can create these automatically. The property below initializes the schema on startup.

# application.properties
spring.batch.jdbc.initialize-schema=always
# Prevent jobs from auto-running on app startup
spring.batch.job.enabled=false

Launching a Job

You execute a Job through a JobLauncher, passing JobParameters. Identifying parameters define the JobInstance; here the run date makes each day a distinct instance.

The launcher returns a JobExecution whose status (COMPLETED, FAILED, STOPPED) reflects the run. All of this is recorded in the JobRepository.

@Component
public class InvoiceJobRunner {
    private final JobLauncher jobLauncher;
    private final Job invoiceJob;

    public InvoiceJobRunner(JobLauncher jobLauncher, Job invoiceJob) {
        this.jobLauncher = jobLauncher;
        this.invoiceJob = invoiceJob;
    }

    public void run(LocalDate date) throws Exception {
        JobParameters params = new JobParametersBuilder()
                .addLocalDate("runDate", date)
                .toJobParameters();
        JobExecution execution = jobLauncher.run(invoiceJob, params);
        System.out.println("Status: " + execution.getStatus());
    }
}

How Restart Uses the Repository

Put the pieces together. When a Job fails mid-run:

  • The failed JobExecution is marked FAILED, but its JobInstance is not marked complete.
  • Each completed Step is recorded; a chunk-oriented step also saved how many items it processed in its ExecutionContext.
  • Re-launching with the same identifying parameters creates a new JobExecution on the same instance. Spring Batch skips already-completed steps and resumes the failed step from the last committed chunk.

This is why identifying parameters and the JobRepository must be stable: they are the coordinates of resumption.

Quick Check

Test your understanding of the job/instance/execution model.

Recap

You now have the structural model of Spring Batch:

  • Job — the top-level process, built with JobBuilder, composed of ordered Steps.
  • JobInstance vs JobExecution — an instance is identified by name + identifying parameters; each run attempt is a separate execution.
  • Step — a phase, either chunk-oriented (read/process/write with a commit interval) or a tasklet (single action); tracked by a StepExecution.
  • JobRepository — persistent metadata in the BATCH_* tables that powers restartability, resume logic, and monitoring.

Master these and the rest of Spring Batch — readers, writers, listeners, partitioning — slots neatly on top.

คำถามที่พบบ่อย

บทเรียน “งาน ขั้นตอน และโมเดล JobRepository” ฟรีหรือไม่

ใช่ — ข้อความเต็มของ “งาน ขั้นตอน และโมเดล JobRepository” ฟรีให้อ่านที่นี่บนเว็บ เพื่อปฏิบัติแบบโต้ตอบ (ตัวแก้ไขโค้ดในตัวและติวเตอร์ AI ตลอด 24/7) และปลดล็อคส่วนที่เหลือของคอร์ส Spring Boot 4 Complete Guide ให้อัปเกรดเป็น CoddyKit PRO คอร์ส Spring Boot 4 Complete Guide มีบทเรียนทั้งหมด 4 บทเรียน

คุณจะเรียนรู้อะไรในบทเรียน “งาน ขั้นตอน และโมเดล JobRepository”

จัดโครงสร้างเวิร์กโหลดแบบแบตช์ด้วยงาน ขั้นตอน และการคงอยู่ของข้อมูลเมตาเพื่อติดตามการทำงาน คุณปฏิบัติ Spring Boot 4 Complete Guide ด้วยโค้ดที่ใช้งานได้จริงที่คุณเรียกใช้โดยตรงในเบราว์เซอร์ และติวเตอร์ AI ตลอด 24/7 ตอบคำถามของคุณขณะที่คุณไปผ่านบทเรียน

คุณต้องมีประสบการณ์ก่อนที่จะเริ่มเรียน Spring Boot 4 Complete Guide หรือไม่

ไม่จำเป็นต้องมีประสบการณ์มาก่อน Spring Boot 4 Complete Guide บน CoddyKit ออกแบบมาสำหรับผู้เริ่มต้นไปจนถึงผู้เรียนขั้นสูง คุณสามารถเริ่มต้นที่นี่หรือเริ่มจากตัวแรกและเรียนด้วยความเร็วของคุณเอง นี่คือบทเรียนที่ 1 จากทั้งหมด 4 บทเรียน

บทเรียน “งาน ขั้นตอน และโมเดล JobRepository” ใช้เวลานานแค่ไหน

บทเรียน CoddyKit ส่วนใหญ่ใช้เวลาประมาณ 5–10 นาที แต่ละบทเรียนจึงสั้นและเป็นแบบโต้ตอบ คุณสามารถก้าวหน้าอย่างต่อเนื่องและกลับมาเรียนต่อจากตรงที่เพิ่งหยุดบนเว็บและแอปได้เลย

ฉันเขียนและรันโค้ดในบทเรียน Spring Boot 4 Complete Guide นี้ได้ไหม

ได้ บทเรียน Spring Boot 4 Complete Guide ทุกบทมีตัวแก้ไขโค้ดในตัว คุณจึงเขียนและรันโค้ดจริงได้เลยในเบราว์เซอร์ และได้รับข้อเสนอแนะจาก AI ในทันที — ไม่ต้องติดตั้งในเครื่องของคุณ

บทเรียนทั้งหมดในหลักสูตรนี้

  1. งาน ขั้นตอน และโมเดล JobRepository
  2. โฟลว์ตัวอ่าน-ตัวประมวลผล-ตัวเขียนแบบแบ่งเป็นชุด
  3. ความทนทานต่อข้อผิดพลาด การข้าม และนโยบายการลองใหม่
  4. การแบ่งพาร์ทิชันและการทำงานขั้นตอนแบบขนาน
← กลับไปที่ Spring Boot 4 Complete Guide