Spring Batch で固定長ファイルを読み込み DB 登録[プログラミング]
(2026-06-24 21:16:57) by shinoda
< ページ移動: 1 2 3 4 >
とは言っても、現時点で最新の Spring Batch 6 ですんなり動くサンプルコードがあまりネット上にもないので、初心者の人にはなんかの参考になるかも(初心者が Spring Batch でバッチなんか作らんやろうというご意見は聞き流します(笑))
■テストデータ(C:\Users\lovelyman\Documents\testdata_20260623_091037.txt)
000000100120260623091102001S00001
000000100120260623091102001E00001
000000110220260623091102001S00001
000000100320260623091102001S00001
000000100320260623091102001E00001
000000110220260623091102001E00001
000000100420260623091102001X00001
000000120520260623091102001S00001
000000120520260623091102001E00001
※トレイルランレースのデータをちょっと加工(笑)
1〜10 ユーザID, 11〜27 測定した時間(ミリ秒 3桁), 28〜28 ステータス, 29〜33 反応回数
■resources/application.properties ※データベースは H2 を使用
spring.application.name=BatchTest3
# H2 を PostgreSQL 互換モードで使用(テーブル名等は小文字で)
spring.datasource.url=jdbc:h2:./.data/h2/db;MODE=PostgreSQL;DATABASE_TO_LOWER=TRUE
spring.datasource.driver-class-name=org.h2.Driver
spring.datasource.username=sa
spring.datasource.password=
# H2 Console を有効化
spring.h2.console.enabled=true
spring.h2.console.path=/h2-console
# JPA/Hibernate設定
spring.jpa.database-platform=org.hibernate.dialect.H2Dialect
spring.jpa.hibernate.ddl-auto=update
spring.jpa.show-sql=true
# バッチ完了後もサーバーを起動したまま(Webコンソール有効状態維持)
spring.batch.job.enabled=true
# Webアプリケーションとして常駐
spring.main.web-application-type=servlet
■Entity/TTimeRecordsEntity.java ※DB の table 構造
package com.netandfield.test.Entity;
import java.time.LocalDateTime;
import jakarta.persistence.Column;
import jakarta.persistence.Entity;
import jakarta.persistence.Id;
import jakarta.persistence.Table;
import lombok.Data;
import lombok.NoArgsConstructor;
@Data
@Entity
@Table(name = "t_time_records")
@NoArgsConstructor
public class TTimeRecordsEntity {
public TTimeRecordsEntity(Integer userId, LocalDateTime keepTime,
String stateCode, Integer readCount) {
this.userId = userId;
this.keepTime = keepTime;
this.stateCode = stateCode;
this.readCount = readCount;
}
// 主キーは userID
@Id
@Column(name = "user_id")
public Integer userId;
@Column(name = "keep_time")
public LocalDateTime keepTime;
@Column(name = "state_code")
public String stateCode;
@Column(name = "read_count")
public Integer readCount;
}