Spring Batch 5.0 Migration Guideを和訳しながら、理解していく

 

遅ればせながら、SpringBatch4系から5系にアップグレードが発生しそうなので、自分用メモ。

 

spring-projectsのspring-batchのSpring Batch 5.0 Migration Guideは英語なので、和訳しながら、コメントをつけていくことで、理解していく。

github.com

 

 

JDK 17 baseline

Spring Batch 5 is based on Spring Framework 6 which requires Java 17 as a minimum version. Therefore, you need to use Java 17+ to run Spring Batch 5 applications.

(和訳)

JDK 17ベースライン

Spring Batch 5は、最小バージョンとしてJava 17を必要とするSpring Framework 6に基づいています。したがって、Spring Batch 5アプリケーションを実行するには、Java 17 +を使用する必要があります。

 

<コメント>

Java17以上を使ってねということ。

Java17未満であれば、先にJavaのバージョンを17以上にする必要がある。

 

Dependencies upgrade

Spring Batch 5 is updating its Spring dependencies across the board to the following versions:

  • Spring Framework 6
  • Spring Integration 6
  • Spring Data 3
  • Spring AMQP 3
  • Spring for Apache Kafka 3
  • Micrometer 1.10

Moreover, this version marks the migration to:

  • Jakarta EE 9: Please make sure to update your import statements from javax.* to jakarta.* for all EE APIs you use.
  • Hibernate 6: Hibernate (cursor/paging) item readers and writer have been updated to use Hibernate 6.1 APIs (previously using Hibernate 5.6 APIs)

In addition to that:

  • org.springframework:spring-jdbc is now a required dependency in spring-batch-core
  • junit:junit is no more a required dependency in spring-batch-test.
  • com.fasterxml.jackson.core:jackson-core is now optional in spring-batch-core

(和訳)

依存関係のアップグレード

Spring Batch 5では、Springの依存関係を以下のバージョンに全面的に更新している:

Spring Framework 6
Spring Integration 6
Spring Data 3
Spring AMQP 3
Spring for Apache Kafka 3
Micrometer 1.10

さらに、このバージョンは、以下への移行を意味する:

Jakarta EE 9:使用するすべてのEE APIについて、import文を javax.* から jakarta.* に更新してください。
Hibernate 6: Hibernate(カーソル/ページング)アイテム・リーダとライタが、Hibernate 6.1 APIを使用するように更新されました(以前はHibernate 5.6 APIを使用していました)。

追加で下記があります。
org.springframework:spring-jdbcは、spring-batch-coreで必須の依存関係になりました。
junit:junitはspring-batch-testの必須依存ではなくなりました。
com.fasterxml.jackson.core:jackson-coreはspring-batch-coreのオプションになりました。

 

<コメント>

・バージョンの更新については、そもそもどういう目的のフレームワークかが分からな時用にリンクを張った。
Micrometerはメトリクスツールで、デフォルトでもJVMや特定のログ、Tomcat、ExecutorService、HTTP Clientのメトリクスが取得できる。

・Jakarta EE 9に関しては、わかりやすくimport文を書き換える必要がある。

・Hibernate 6.1 APIとHibernate 5.6 APIの違いについては、Migration Guideを張っておく。cursorを見る限りは、5.66.1にそんなに違いがないかも?

・依存関係系は、org.springframework:spring-jdbcは必須化、junit:junitとcom.fasterxml.jackson.core:jackson-coreの依存関係が軽くなった。

 

Database schema update

(和訳)

データベーススキーマの更新

 

<コメント>

ちょっと長いので、DB毎に分割する

 

Oracle

In this version, Oracle sequences are now ordered. The sequences creation script has been updated for new applications. Existing applications can use the migration script in org/springframework/batch/core/migration/5.0/migration-oracle.sql to alter the existing sequences.

Moreover, the DDL scripts for Oracle have been renamed as follows:

  • org/springframework/batch/core/schema-drop-oracle10g.sql has been renamed to org/springframework/batch/core/schema-drop-oracle.sql
  • org/springframework/batch/core/schema-oracle10g.sql has been renamed to org/springframework/batch/core/schema-oracle.sql

(和訳)

オラクル


このバージョンでは、Oracleシーケンスが順番に並べられるようになりました。シーケンス作成スクリプトが新しいアプリケーション用に更新されました。既存のアプリケーションでは、org/springframework/batch/core/migration/5.0/migration-oracle.sql にある移行スクリプトを使用して、既存のシーケンスを変更できます。

さらに、Oracle用のDDLスクリプトの名前が以下のように変更されました:

org/springframework/batch/core/schema-drop-oracle10g.sql は org/springframework/batch/core/schema-drop-oracle.sql に名前が変更されました。
org/springframework/batch/core/schema-oracle10g.sql は org/springframework/batch/core/schema-oracle.sql に名前が変更されました。

 

<コメント>

・シーケンスに関する変更があった様子。また、スクリプト名が変更。

移行スクリプトを実行する必要があるので、リリースタイミング等に影響ありそう。

 

MS SQLServer

Up until v4, the DDL script for MS SQLServer used tables to emulate sequences. In this version, this usage has been updated with real sequences:

CREATE SEQUENCE BATCH_STEP_EXECUTION_SEQ START WITH 0 MINVALUE 0 MAXVALUE 9223372036854775807 NO CACHE NO CYCLE;
CREATE SEQUENCE BATCH_JOB_EXECUTION_SEQ START WITH 0 MINVALUE 0 MAXVALUE 9223372036854775807 NO CACHE NO CYCLE;
CREATE SEQUENCE BATCH_JOB_SEQ START WITH 0 MINVALUE 0 MAXVALUE 9223372036854775807 NO CACHE NO CYCLE;
 

New applications can use the provided script with no modifications. Existing applications should consider modifying the snippet above to start sequences from the last value in sequence tables used with v4.

(和訳)

MS SQLServer


v4 までは、MS SQLServer 用の DDL スクリプトはシーケンスをエミュレートするためにテーブルを使用していました。このバージョンでは、この使用法が実際のシーケンスに更新されました:

(省略)

新規アプリケーションは、提供されたスクリプトを使用することができます;
新しいアプリケーションは、提供されたスクリプトを修正することなく使用できます。既存のアプリケーションは、v4で使用されるシーケンス・テーブルの最後の値からシーケンスを開始するように、上記のスニペットを修正することを検討してください。

 

<コメント>

・こちらもシーケンスの扱いが変更。

・現状に合わせて、「シーケンス・テーブルの最後の値からシーケンスを開始」させるのは、ちょっと面倒。

 

 

All platforms

Removal of BATCH_JOB_EXECUTION#JOB_CONFIGURATION_LOCATION column

The column JOB_CONFIGURATION_LOCATION in the BATCH_JOB_EXECUTION table is not used anymore and can be marked as unused or dropped if needed:

ALTER TABLE BATCH_JOB_EXECUTION DROP COLUMN JOB_CONFIGURATION_LOCATION;
 

The syntax to drop the column might differ depending on the version of your database server, so please check the syntax of column deletion. This change might require a table reorganisation on some platforms.

❗ Important note ❗ This change is mainly related to the removal of the JSR-352 implementation which was the only part of the framework using this column. As a consequence, the field JobExecution#jobConfigurationName has been removed as well as all APIs using it (constructors and getter in the domain object JobExecution, method JobRepository#createJobExecution(JobInstance, JobParameters, String); in JobRepository).

(和訳)

すべてのプラットフォーム


BATCH_JOB_EXECUTION#JOB_CONFIGURATION_LOCATION列の削除
BATCH_JOB_EXECUTIONテーブルのJOB_CONFIGURATION_LOCATION列は使用されなくなりました:

(省略)

カラムを削除する構文はデータベースサーバーのバージョンによって異なる可能性があるので、カラム削除の構文を確認してください。この変更により、プラットフォームによってはテーブルの再編成が必要になるかもしれません。

❗ 重要な注意❗ この変更は主に、このカラムを使用していたフレームワークの唯一の部分であった JSR-352 実装の削除に関連しています。その結果、JobExecution#jobConfigurationName フィールドが削除され、それを使用するすべての API(ドメインオブジェクト JobExecution のコンストラクタとゲッター、JobRepository#createJobExecution(JobInstance, JobParameters, String); in JobRepository)も削除されました。

 

<コメント>

・BATCH_JOB_EXECUTIONは、JobRepositoryのメタデータテーブルの一つ。メタデータテーブルに関しては、下記を参照。

メタデータスキーマ :: Spring Batch - リファレンス

Spring Batchのアーキテクチャ

BATCH_JOB_EXECUTION.JOB_CONFIGURATION_LOCATIONをdropしてねということ。

また、JobRepository#createJobExecution(JobInstance, JobParameters, String)が削除されているので、注意。

・JSR-352については、JavaEEの標準バッチAPIのこと。JobやChunk、Stepのような概念はここからきている。詳しくは、下記を参照。

Java EE の標準バッチAPI -- JSR-352 Batch Applications for the Java Platform -- - A Memorandum

 

Column change in BATCH_JOB_EXECUTION_PARAMS

The BATCH_JOB_EXECUTION_PARAMS has been updated as follows:

CREATE TABLE BATCH_JOB_EXECUTION_PARAMS  (
	JOB_EXECUTION_ID BIGINT NOT NULL ,
---	TYPE_CD VARCHAR(6) NOT NULL ,
---	KEY_NAME VARCHAR(100) NOT NULL ,
---	STRING_VAL VARCHAR(250) ,
---	DATE_VAL DATETIME(6) DEFAULT NULL ,
---	LONG_VAL BIGINT ,
---	DOUBLE_VAL DOUBLE PRECISION ,
+++	PARAMETER_NAME VARCHAR(100) NOT NULL ,
+++	PARAMETER_TYPE VARCHAR(100) NOT NULL ,
+++	PARAMETER_VALUE VARCHAR(2500) ,
	IDENTIFYING CHAR(1) NOT NULL ,
	constraint JOB_EXEC_PARAMS_FK foreign key (JOB_EXECUTION_ID)
	references BATCH_JOB_EXECUTION(JOB_EXECUTION_ID)
);
 

This is related to the way job parameters are persisted as revisited in https://github.com/spring-projects/spring-batch/issues/3960. Migration scripts can be found in org/springframework/batch/core/migration/5.0.

(和訳)

BATCH_JOB_EXECUTION_PARAMSのカラム変更
BATCH_JOB_EXECUTION_PARAMSが以下のように更新されました:

(省略)

これは、https://github.com/spring-projects/spring-batch/issues/3960 で再確認したように、ジョブパラメータが永続化される方法に関連しています。移行スクリプトはorg/springframework/batch/core/migration/5.0にあります。

 

<コメント>

・BATCH_JOB_EXECUTION_PARAMSもJobRepositoryのメタデータテーブルの一つ。

テーブル定義に変更があるので、移行スクリプトを利用するとよい。

 

 

Column change in BATCH_STEP_EXECUTION

A new column CREATE_TIME was added in v5. You should create it in the table according to your database server, something like:

ALTER TABLE BATCH_STEP_EXECUTION ADD CREATE_TIME TIMESTAMP NOT NULL DEFAULT '1970-01-01 00:00:00';
 

Moreover, the NOT NULL constraint was dropped from the START_TIME column:

ALTER TABLE BATCH_STEP_EXECUTION ALTER COLUMN START_TIME DROP NOT NULL;
 

(和訳)

BATCH_STEP_EXECUTIONにおけるカラムの変更

v5で新しいカラムCREATE_TIMEが追加された:

(省略)
さらに、START_TIME列からNOT NULL制約が削除された:
(省略)

 

<コメント>

・BATCH_STEP_EXECUTIONもJobRepositoryのメタデータテーブルの一つ。

定義が変更されているので、使用箇所の調査対象となる。

 

Infrastructure beans configuration with @EnableBatchProcessing

(和訳)

EnableBatchProcessingによるインフラビーンズの設定

 

<コメント>

・EnableBatchProcessingはSpring Boot の Spring Batch の自動構成を有効にするアノテーション。
この変更が破壊的なものであるため、移行時には注意が必要な部分。

Spring Boot 3にアップデートしたらSpring Batchが動かなくなった

 

Job repository/explorer configuration updates

The Map-based job repository/explorer implementation were deprecated in v4 and completely removed in v5. You should use the Jdbc-based implementation instead. Unless you are using a custom Job repository/explorer implementation, the @EnableBatchProcessing annotation will configure a Jdbc-based JobRepository which requires a DataSource bean in the application context. The DataSource bean could refer to an embedded database like H2, HSQL, etc to work with an in-memory job repository

(和訳)

ジョブリポジトリ/エクスプローラ設定の更新


Map ベースのジョブ・リポジトリ/エクスプローラの実装は v4 で非推奨となり、v5 で完全に削除されました。 代わりに Jdbc ベースの実装を使用する必要があります。

カスタムのジョブリポジトリ/エクスプローラ実装を使用していない限り、@EnableBatchProcessing アノテーションはアプリケーションコンテキストに DataSource Bean を必要とする Jdbc ベースのジョブリポジトリを構成します。

DataSource BeanはH2やHSQLなどの組み込みデータベースを参照し、インメモリジョブリポジトリと連携することができます。

 

<コメント>

・今までメタテーブルに関する情報を使用しないことができたが、今回のバージョンアップで、できなくなった。

考えられる対応策としては、①記載の通りH2やHSQLなどの組み込みデータベースを利用するか、②既に存在するDBにメタテーブルを作成することになりそう。
ちなみに、H2については、最新バージョンだとダメという情報もある。

【SpringBatch】メタデータテーブルをDBに生成せずに済ませるには(検証ソースあり) - HIRO Tracks

 

 

Transaction manager bean exposure/configuration

Up until version 4.3, the @EnableBatchProcessing annotation exposed a tranasaction manager bean in the application context. While this was convenient in many cases, the unconditional exposure of a tranasaction manager could interfere with a user-defined transaction manager. In this release, @EnableBatchProcessing does not expose a transaction manager bean in the application context anymore. This change is related to issue https://github.com/spring-projects/spring-batch/issues/816.

As a result of the aforementioned issue, and in combination with the inconsistency between the XML and Java config styles regarding the transaction manager that was fixed in https://github.com/spring-projects/spring-batch/issues/4130, it is now required to manually configure the transaction manager on any tasklet step definition. The method StepBuilderHelper#transactionManager(PlatformTransactionManager) was moved down a level, to AbstractTaskletStepBuilder.

The typical migration path from v4 to v5 in that regard is as follows:

// Sample with v4
@Configuration
@EnableBatchProcessing
public class MyStepConfig {

    @Autowired
    private StepBuilderFactory stepBuilderFactory;

    @Bean
    public Step myStep() {
        return this.stepBuilderFactory.get("myStep")
                .tasklet(..) // or .chunk()
                .build();
    }

}
 
// Sample with v5
@Configuration
@EnableBatchProcessing
public class MyStepConfig {

    @Bean
    public Tasklet myTasklet() {
       return new MyTasklet();
    }

    @Bean
    public Step myStep(JobRepository jobRepository, Tasklet myTasklet, PlatformTransactionManager transactionManager) {
        return new StepBuilder("myStep", jobRepository)
                .tasklet(myTasklet, transactionManager) // or .chunk(chunkSize, transactionManager)
                .build();
    }

}
 

This is only required for tasklet steps, other step types do not require a transaction manager by design.

Moreover, the transaction manager was configurable by implementing BatchConfigurer#getTransactionManager. The transaction manager being an implementation detail of the JobRepository, it should not be configurable at the same level as the JobRepository (ie in the same interface). In this release, the BatchConfigurer interface was removed. If needed, a custom transaction manager could be supplied either declaratively as an attribute of @EnableBatchProcessing, or programmatically by overriding DefaultBatchConfiguration#getTransactionManager(). For more details about this change, please check https://github.com/spring-projects/spring-batch/issues/3942.

(和訳)

トランザクション・マネージャ・ビーンの公開/構成


バージョン 4.3 までは、@EnableBatchProcessing アノテーションはアプリケーション・コンテキストでトランザクション・マネージャ Bean を公開していました。これは多くの場合に便利でしたが、トランザクション・マネジャーを無条件に公開すると、ユーザー定義のトランザクション・マネジャーと干渉する可能性がありました。このリリースでは、@EnableBatchProcessing はアプリケーション・コンテキストでトランザクション・マネージャ・ビーンを公開しません。この変更は、問題 https://github.com/spring-projects/spring-batch/issues/816 に関連しています。

前述の問題と、https://github.com/spring-projects/spring-batch/issues/4130 で修正されたトランザクション・マネージャに関する XML 構成スタイルと Java 構成スタイルの不一致の結果として、タスクレット・ステップ定義でトランザクション・マネージャを手動で構成する必要があります。StepBuilderHelper#transactionManager(PlatformTransactionManager)メソッドは、AbstractTaskletStepBuilderにレベルダウンされました。

v4からv5への典型的な移行パスは以下の通りです:

(省略)

これはタスクレットステップにのみ必要で、他のステップタイプは設計上トランザクションマネージャーを必要としない。

さらに、トランザクション・マネージャーはBatchConfigurer#getTransactionManagerを実装することで設定可能であった。トランザクション・マネージャーはJobRepositoryの実装の詳細であるため、JobRepositoryと同じレベルで(つまり同じインターフェースで)設定できるべきではありません。このリリースでは、BatchConfigurer インターフェースは削除されました。必要であれば、@EnableBatchProcessingの属性として宣言的に、またはDefaultBatchConfiguration#getTransactionManager()をオーバーライドしてプログラム的に、カスタムトランザクションマネージャを提供することができます。この変更の詳細については、https://github.com/spring-projects/spring-batch/issues/3942

 

<コメント>

・TransactionManagerの変更で、どうしても設定を変えたい場合は、DefaultBatchConfiguration#getTransactionManager()をオーバーライドしろということ。合わせて、BatchConfigurerが削除。

・例の通りStepの定義が変わっていて、引数が変わっているので、この辺の対応が必要。

 

JobBuilderFactory and StepBuilderFactory bean exposure/configuration

JobBuilderFactory and StepBuilderFactory are not exposed as beans in the application context anymore, and are now deprecated for removal in v5.2 in favor of using the respective builders they create.

The typical migration path from v4 to v5 in that regard is as follows:

// Sample with v4
@Configuration
@EnableBatchProcessing
public class MyJobConfig {

    @Autowired
    private JobBuilderFactory jobBuilderFactory;

    @Bean
    public Job myJob(Step step) {
        return this.jobBuilderFactory.get("myJob")
                .start(step)
                .build();
    }

}
 
// Sample with v5
@Configuration
@EnableBatchProcessing
public class MyJobConfig {

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

}
 

The same pattern can be used to remove the usage of the deprecated StepBuilderFactory. For more details about this change, please check https://github.com/spring-projects/spring-batch/issues/4188.

(和訳)

JobBuilderFactory と StepBuilderFactory ビーンの公開/設定

JobBuilderFactoryとStepBuilderFactoryはアプリケーションコンテキストでBeanとして公開されなくなり、v5.2では削除されました。

この点に関するv4からv5への典型的な移行パスは以下の通りです:

(省略)

同じパターンを使って、非推奨のStepBuilderFactoryの使用を削除することができる。この変更の詳細については、https://github.com/spring-projects/spring-batch/issues/4188

 

<コメント>

・Jobの定義方法が変わった。引数にjobRepositoryが増えている。

・StepBuilderFactoryの削除の例は、Transaction manager bean exposure/configurationの項にあるので、参照。StepBuilderFactoryは削除しても、何とかなるようになった。

 

 

Data types updates

  • Metric counters (readCountwriteCount, etc) in org.springframework.batch.core.StepExecution and org.springframework.batch.core.StepContribution have been changed from int to long. All getters and setters have been updated accordingly.
  • The skipCount parameter in org.springframework.batch.core.step.skip.SkipPolicy#shouldSkip has been changed from int to long. This is related to the previous point.
  • The type of fields startTimeendTimecreateTime and lastUpdated in JobExecution and StepExecution was changed from java.util.Date to java.time.LocalDateTime.

(和訳)

データ型の更新


org.springframework.batch.core.StepExecutionとorg.springframework.batch.core.StepContributionのメトリックカウンタ(readCount, writeCountなど)がintからlongに変更されました。すべてのゲッターとセッターはそれに合わせて更新されました。
org.springframework.batch.core.step.skip.SkipPolicy#shouldSkipのskipCountパラメータがintからlongに変更された。これは前の点と関連している。
JobExecutionとStepExecutionのフィールドstartTime、endTime、createTime、lastUpdatedの型がjava.util.Dateからjava.time.LocalDateTimeに変更された。

 

<コメント>

・型の変更なので、既存からわかりやすくコンパイルエラーになりそう。

 

Observability updates

  • Micrometer has been updated to version 1.10
  • All tags are now prefixed with the meter name. For example, the tags of the timer spring.batch.job are named name and status in version 4.x. In version 5, those tags are now named spring.batch.job.name and spring.batch.job.status respectively.
  • The BatchMetrics class (which is intended for internal use only) has been moved from org.springframework.batch.core.metrics to the org.springframework.batch.core.observability package.

(和訳)

観測可能性の更新


Micrometerがバージョン1.10に更新されました。
すべてのタグの先頭にメーター名が付くようになりました。例えば、spring.batch.jobというタイマーのタグはバージョン4.xではnameとstatusという名前でしたが、バージョン5ではそれぞれspring.batch.job.nameとspring.batch.job.statusという名前になりました。
BatchMetricsクラス(内部使用のみ)はorg.springframework.batch.core.metricsからorg.springframework.batch.core.observabilityパッケージに移動しました。

 

<コメント>

・Micrometerに関する更新。

 

Execution context serialization updates

Starting from v5, the default ExecutionContextSerializer was changed from JacksonExecutionContextStringSerializer to DefaultExecutionContextSerializer. The default execution context serializer was updated to serialize/deserialize the context to/from Base64.

The dependency to Jackson was made optional. In order to use the JacksonExecutionContextStringSerializerjackson-core should be added to the classpath.

(和訳)

実行コンテキスト・シリアライズの更新


v5 から、デフォルトの ExecutionContextSerializer が JacksonExecutionContextStringSerializer から DefaultExecutionContextSerializer に変更されました。デフォルトの実行コンテキスト・シリアライザーが更新され、コンテキストを Base64 にシリアライズ/Base64 からシリアライズ解除するようになりました。

Jackson への依存関係がオプションになりました。JacksonExecutionContextStringSerializer を使用するには、jackson-core をクラスパスに追加する必要があります。

 

<コメント>

・ExecutionContextSerializerは、実行コンテキストの直列化と逆直列化の両方を単一の実装に組み合わせた複合インターフェース。

 

 

SystemCommandTasklet updates

The SystemCommandTasklet has been revisited in this release and was changed as follows:

  • A new strategy interface named CommandRunner was introduced in order to decouple the command execution from the tasklet execution. The default implementation is the JvmCommandRunner which uses the java.lang.Runtime#exec API to run system commands. This interface can be implemented to use any other API to run system commands.

  • The method that runs the command now accepts an array of Strings representing the command and its arguments. There is no need anymore to tokenize the command or do any pre-processing. This change makes the API more intuitive, and less prone to errors.

(和訳)

SystemCommandTasklet のアップデート


今回のリリースでは、SystemCommandTaskletが見直され、以下のように変更されました:

コマンドの実行をタスクレットの実行から切り離すために CommandRunner という新しいストラテジインタフェースが導入されました。デフォルトの実装はJvmCommandRunnerで、java.lang.Runtime#exec APIを使ってシステムコマンドを実行します。このインタフェースは、システムコマンドを実行するために他のAPIを使用するように実装することができます。

コマンドを実行するメソッドは、コマンドとその引数を表す文字列の配列を受け取ります。コマンドをトークン化したり、前処理をしたりする必要はなくなった。この変更により、APIはより直感的になり、エラーが発生しにくくなりました。

 

<コメント>

・SystemCommandTaskletはその名の通り、システムコマンドを実行するタスクレット。

 

 

Job parameters handling updates

(和訳)

ジョブ・パラメータの更新

 

<コメント>

・ここのも多いので、セクションごとにに分ける。

 

 

Support for any type as a job parameter

This change adds support to use any type as a job parameter, and not only the 4 pre-defined types (long, double, string, date) as in v4. The main change in the following:

---public class JobParameter implements Serializable {
+++public class JobParameter<T> implements Serializable {

---   private Object parameter;
+++   private T value;

---   private ParameterType parameterType;
+++   private Class<T> type;

}
 

With this revision, the JobParameter can be of any type. This change required many API changes like changing the return type of getType(), or the removal of the ParameterType enum. All changes related to this update can be found in the "[Deprecated|Moved|Removed] APIs" sections.

This change had an impact on how job parameters are persisted in the database (There are no more 4 distinct columns for each predefined type). Please check Column change in BATCH_JOB_EXECUTION_PARAMS for DDL changes. The fully qualified name of the type of the parameter is now persisted as a String, as well as the parameter value. String literals are converted to the parameter type with the standard Spring conversion service. The standard conversion service can be enriched with any required converter to convert user specific types to and from String literals.

(和訳)

ジョブパラメータとしての任意の型のサポート

この変更により、v4のようにあらかじめ定義された4つの型(long, double, string, date)だけでなく、任意の型をジョブパラメータとして使用できるようになりました:

(省略)

この改訂により、JobParameter は任意の型にすることができるようになりました。この変更により、getType() の戻り値の型の変更や、ParameterType 列挙型の削除など、多くの API の変更が必要になりました。この更新に関連するすべての変更は、"[Deprecated|Moved|Removed] APIs" セクションにあります。

 

この変更は、ジョブパラメータがデータベースに永続化される方法に影響を及ぼしました (定義済みの型ごとに4つの異なるカラムがなくなりました)。DDLの変更については、BATCH_JOB_EXECUTION_PARAMSの列の変更を確認してください。パラメータの型の完全修飾名が、パラメータ値と同様にStringとして永続化されるようになりました。文字列リテラルは、Springの標準変換サービスでパラメータ型に変換されます。標準の変換サービスは、ユーザー固有の型をStringリテラルに変換したり、Stringリテラルから変換したりするために必要なコンバータで強化することができます。

 

<コメント>

・ジョブパラメーターの型の縛りがなかったので、自由になったともいえるが、BATCH_JOB_EXECUTION_PARAMSに影響を与えていて、型でオリジナリティを出すと、変換コンバーターが必要になる。

 

Default job parameter conversion

The default notation of job parameters in v4 was specified as follows:

[+|-]parameterName(parameterType)=value
 

where parameterType is one of [string,long,double,date]. In addition to be limited and constraining, this notation caused several issues as described in https://github.com/spring-projects/spring-batch/issues/3960.

In v5, there are two way to specify job parameters:

Default notation

The default notation is specified as follows:

parameterName=parameterValue,parameterType,identificationFlag
 

where parameterType is the fully qualified name of the type of the parameter. Spring Batch provides the DefaultJobParametersConverter to support this notation.

Extended notation

While the default notation is well suited for the majority of use cases, it might be inconvenient when the value contains a comma for example. In this case, the extended notation can be used, which is inspired by Spring Boot's Json Application Properties and specified as follows:

parameterName='{"value": "parameterValue", "type":"parameterType", "identifying": "booleanValue"}'
 

where parameterType is the fully qualified name of the type of the parameter. Spring Batch provides the JsonJobParametersConverter to support this notation.

(和訳)

ジョブパラメータのデフォルト変換

v4におけるジョブ・パラメータのデフォルト表記は以下のように規定されている:

[parameterName(parameterType)=value
ここで、parameterTypeは[string,long,double,date]のいずれかです。限定的で制約の多いこの表記法は、https://github.com/spring-projects/spring-batch/issues/3960 で説明されているように、いくつかの問題を引き起こしていました。

v5では、ジョブパラメータを指定する2つの方法があります:

 

デフォルト表記法

デフォルトの表記方法は以下の通りです:

parameterName=parameterValue,parameterType,identificationFlag
ここで、parameterTypeはパラメータの型の完全修飾名です。Spring Batchはこの表記法をサポートするDefaultJobParametersConverterを提供します。

 

拡張表記法

 

デフォルトの記法は大半のユースケースに適していますが、例えば値にカンマが含まれている場合は不便かもしれません。この場合、Spring BootのJson Application Propertiesにヒントを得た拡張記法を使うことができ、次のように指定します:

parameterName='{"value":parameterName='{"value": "parameterValue", "type": "parameterType", "identifying":"booleanValue"}'
ここで、parameterTypeはパラメータの型の完全修飾名です。Spring Batchはこの記法をサポートするJsonJobParametersConverterを提供します。

 

<コメント>

・これはジョブを起動する際に、アプリケーションに引き渡すパラメーターのお話。

SpringBootを起動する際に引き渡すパラメーターの型を説明している。

かなり複雑なものも対応できるように見える。

 

Historical data access implications

Due to this breaking change about handling job parameters, some APIs that are designed to explore batch meta-data should not be used for job instances that were launched with v4. For example:

  • JobExplorer#getJobInstances could retrieve a mix of historical data between v4 and v5 and might fails at loading job parameters of v4 (#4352). In this particular case, make sure to start at the index of the first instance executed with v5.
  • JobExplorer#getJobExecution could fail at retrieving job parameters if the passed job execution ID is one of an execution that was run with v4.

Another case where this change has implications on loading job parameters is when restarting failed job instances. It is expected that all failed v4 job instances are either restarted to success or abandoned before the migration to v5 is done.

(和訳)

履歴データアクセスへの影響

ジョブパラメータの取り扱いに関するこの変更により、バッチメタデータを探索するように設計されたいくつかのAPIは、v4で起動されたジョブインスタンスには使用できません。 たとえば、以下のようなものです:

JobExplorer#getJobInstancesはv4とv5の履歴データを混在して取得する可能性があり、v4のジョブパラメータの読み込みに失敗する可能性があります(#4352)。このような場合は、v5で最初に実行されたインスタンスのインデックスから開始するようにしてください。


渡されたジョブ実行IDがv4で実行されたものである場合、JobExplorer#getJobExecutionはジョブパラメータの取得に失敗する可能性があります。
この変更がジョブパラメータのロードに影響するもう1つのケースは、失敗したジョブインスタンスを再起動する場合です。v5への移行が完了する前に、すべての失敗したv4ジョブインスタンスが成功するように再起動されるか、放棄されることが期待されます。

 

<コメント>

・v4のジョブパラメーターで起動したデータが残っていると、v5で失敗する可能性があると…

結構な負の遺産なのと、環境によっては、バッチが起動しないみたいなことが発生しそうなので、要注意。

 

 

Deprecated APIs

(和訳)

・非推奨API

 

<コメント>

・そのうち消えるので、使っていたら要注意。

 

The following APIs have been deprecated in version 5.0:

  • org.springframework.batch.core.listener.ChunkListenerSupport
  • org.springframework.batch.core.listener.StepExecutionListenerSupport
  • org.springframework.batch.repeat.listener.RepeatListenerSupport
  • org.springframework.batch.core.listener.JobExecutionListenerSupport
  • org.springframework.batch.core.listener.SkipListenerSupport
  • org.springframework.batch.item.data.Neo4jItemReader
  • org.springframework.batch.item.data.builder.Neo4jItemWriterBuilder
  • org.springframework.batch.item.data.Neo4jItemWriter
  • org.springframework.batch.item.data.builder.Neo4jItemWriterBuilder
  • org.springframework.batch.item.database.support.SqlPagingQueryUtils#generateLimitGroupedSqlQuery(org.springframework.batch.item.database.support.AbstractSqlPagingQueryProvider, boolean, java.lang.String)
  • org.springframework.batch.core.repository.dao.JdbcJobInstanceDao#setJobIncrementer(DataFieldMaxValueIncrementer jobIncrementer)
  • org.springframework.batch.core.launch.support.SimpleJobLauncher
  • org.springframework.batch.core.configuration.annotation.JobBuilderFactory
  • org.springframework.batch.core.configuration.annotation.StepBuilderFactory
  • The constructor org.springframework.batch.core.job.builder.JobBuilder#JobBuilder(java.lang.String)
  • The constructor org.springframework.batch.core.step.builder.StepBuilder#StepBuilder(java.lang.String)
  • The method org.springframework.batch.core.step.builder.StepBuilder#tasklet(org.springframework.batch.core.step.tasklet.Tasklet)
  • The method org.springframework.batch.core.step.builder.StepBuilder#chunk(int)
  • The method org.springframework.batch.core.step.builder.StepBuilder#chunk(org.springframework.batch.repeat.CompletionPolicy)
  • The method org.springframework.batch.core.step.builder.TaskletStepBuilder#tasklet(org.springframework.batch.core.step.tasklet.Tasklet)
  • The constructor org.springframework.batch.integration.chunk.RemoteChunkingManagerStepBuilder#RemoteChunkingManagerStepBuilder(java.lang.String)
  • The constructor org.springframework.batch.integration.partition.RemotePartitioningManagerStepBuilder#RemotePartitioningManagerStepBuilder(java.lang.String)
  • The constructor org.springframework.batch.integration.partition.RemotePartitioningWorkerStepBuilder#RemotePartitioningWorkerStepBuilder(java.lang.String)
  • The method org.springframework.batch.integration.partition.RemotePartitioningWorkerStepBuilder#tasklet(org.springframework.batch.core.step.tasklet.Tasklet)
  • The method org.springframework.batch.integration.partition.RemotePartitioningWorkerStepBuilder#chunk(int)
  • The method org.springframework.batch.integration.partition.RemotePartitioningWorkerStepBuilder#chunk(org.springframework.batch.repeat.CompletionPolicy)
  • The method org.springframework.batch.core.JobParameters#toProperties
  • The method org.springframework.batch.core.JobParametersBuilder#addParameter
  • The class org.springframework.batch.core.launch.support.JobRegistryBackgroundJobRunner
  • The class org.springframework.batch.test.DataSourceInitializer
  • The class org.springframework.batch.integration.step.DelegateStep
  • The annotation org.springframework.batch.support.annotation.Classifier
  • The class org.springframework.batch.item.ItemStreamSupport
  • The method org.springframework.batch.core.step.builder.AbstractTaskletStepBuilder#throttleLimit
  • The method org.springframework.batch.repeat.support.TaskExecutorRepeatTemplate#setThrottleLimit
  • The interface org.springframework.batch.repeat.support.ResultHolder
  • The interface org.springframework.batch.repeat.support.ResultQueue
  • The class org.springframework.batch.repeat.support.ResultHolderResultQueue
  • The class org.springframework.batch.repeat.support.ThrottleLimitResultQueue

Please refer to the Javadoc of each API for more details about the suggested replacement.

(和訳)

推奨される置き換えの詳細については、各APIのJavadocを参照のこと。

 

<コメント>

・Javadoc見ましょう。

 

Moved APIs

(和訳)

・移動したAPI

 

<コメント>

・使っていたら、import文のパッケージの変更が必要となりそう。

 

  • The BatchMetrics class (which is intended for internal use only) has been moved from org.springframework.batch.core.metrics to the org.springframework.batch.core.observability package.
  • The Chunk class was moved from the org.springframework.batch.core.step.item package (spring-batch-core module) to the org.springframework.batch.item package (spring-batch-infrastrucutre module)
  • The ScopeConfiguration class has moved from org.springframework.batch.core.configuration.annotation to org.springframework.batch.core.configuration.support

 

Removed APIs

(和訳)

削除されたAPI

 

<コメント>

・バージョンアップすると、使えません。

 

  • Class org.springframework.batch.core.repository.support.MapJobRepositoryFactoryBean
  • Class org.springframework.batch.core.repository.dao.MapExecutionContextDao
  • Class org.springframework.batch.core.repository.dao.MapJobExecutionDao
  • Class org.springframework.batch.core.repository.dao.MapJobInstanceDao
  • Class org.springframework.batch.core.repository.dao.MapStepExecutionDao
  • Class org.springframework.batch.core.explore.support.MapJobExplorerFactoryBean
  • Class org.springframework.batch.core.repository.dao.XStreamExecutionContextStringSerializer
  • Class org.springframework.batch.core.configuration.support.ClassPathXmlJobRegistry
  • Class org.springframework.batch.core.configuration.support.ClassPathXmlApplicationContextFactory
  • Class org.springframework.batch.core.launch.support.ScheduledJobParametersFactory
  • Class org.springframework.batch.item.data.AbstractNeo4jItemReader
  • Class org.springframework.batch.item.database.support.ListPreparedStatementSetter
  • Class org.springframework.batch.integration.chunk.RemoteChunkingMasterStepBuilder
  • Class org.springframework.batch.integration.chunk.RemoteChunkingMasterStepBuilderFactory
  • Class org.springframework.batch.integration.partition.RemotePartitioningMasterStepBuilder
  • Class org.springframework.batch.integration.partition.RemotePartitioningMasterStepBuilderFactory
  • Class org.springframework.batch.test.AbstractJobTests
  • Class org.springframework.batch.item.xml.StaxUtils

 

<コメント>

・代替手段がないものもあるのか、要注意。

 

  • Enum org.springframework.batch.item.file.transform.Alignment
  • Enum org.springframework.batch.core.JobParameter#ParameterType

<コメント>

・使う必要がなくなったEnum。多分、廃止されたClass関連のもの。

 

  • Method org.springframework.batch.core.JobExecution#stop()
  • Method org.springframework.batch.core.JobParameters#getDouble(String key, double defaultValue)
  • Method org.springframework.batch.core.JobParameters#getLong(String key, long defaultValue)
  • Method org.springframework.batch.core.partition.support.SimpleStepExecutionSplitter(JobRepository jobRepository, Step step, Partitioner partitioner)
  • Method org.springframework.batch.core.partition.support.SimpleStepExecutionSplitter#getStartable(StepExecution stepExecution, ExecutionContext context)
  • Method org.springframework.batch.core.repository.support.AbstractJobRepositoryFactoryBean#getJobRepository()
  • Method org.springframework.batch.item.database.AbstractCursorItemReader#cleanupOnClose()
  • Method org.springframework.batch.item.database.HibernateItemWriter#doWrite(HibernateOperations hibernateTemplate, List<? extends T> items)
  • Method org.springframework.batch.item.database.JdbcCursorItemReader#cleanupOnClose()
  • Method org.springframework.batch.item.database.StoredProcedureItemReader#cleanupOnClose()
  • Method org.springframework.batch.item.database.builder.HibernatePagingItemReaderBuilder#useSatelessSession(boolean useStatelessSession)
  • Method org.springframework.batch.item.file.MultiResourceItemReader#getCurrentResource()
  • Method org.springframework.batch.integration.config.annotation.BatchIntegrationConfiguration#remoteChunkingMasterStepBuilderFactory()
  • Method org.springframework.batch.integration.config.annotation.BatchIntegrationConfiguration#remotePartitioningMasterStepBuilderFactory()
  • Method org.springframework.batch.item.util.FileUtils#setUpOutputFile(File file, boolean restarted, boolean overwriteOutputFile)

<コメント>

・メソッドは引数が変わっている等ありえるので、同じメソッド名で確認する。

 

Moreover, the following APIs have been removed/updated without deprecation:

  • The interface org.springframework.batch.core.configuration.annotation.BatchConfigurer was removed. See https://github.com/spring-projects/spring-batch/issues/3942
  • The class org.springframework.batch.core.configuration.annotation.DefaultBatchConfigurer was removed. See https://github.com/spring-projects/spring-batch/issues/3942
  • The method org.springframework.batch.core.step.builder.SimpleStepBuilder#processor(Function) has been removed to allow lambdas to be passed as item processors. See https://github.com/spring-projects/spring-batch/issues/4061 for more details about the rationale behind this removal. If you use an actual Function as argument for SimpleStepBuilder::processor, then you can change that to .processor(function::apply) to migrate to v5.
  • org.springframework.batch.item.file.builder.FlatFileItemWriterBuilder#resourceorg.springframework.batch.item.file.ResourceAwareItemWriterItemStream#setResourceorg.springframework.batch.item.json.builder.JsonFileItemWriterBuilder#resourceorg.springframework.batch.item.json.JsonFileItemWriter#JsonFileItemWriterorg.springframework.batch.item.support.AbstractFileItemWriter#setResourceorg.springframework.batch.item.xml.builder.StaxEventItemWriterBuilder#resource and org.springframework.batch.item.xml.StaxEventItemWriter#setResource have been updated to accept a org.springframework.core.io.WritableResource instead of a org.springframework.core.io.Resource. For more details about this change, please check https://github.com/spring-projects/spring-batch/issues/756
  • The static type org.springframework.batch.item.data.builder.RepositoryItemReaderBuilder.RepositoryMethodReference along with the method org.springframework.batch.item.data.builder.RepositoryItemReaderBuilder#repository(RepositoryMethodReference<?>) have been removed.
  • The signature of the method ItemWriter#write(List) was changed to ItemWriter#write(Chunk)
  • All implementations of ItemWriter were updated to use the Chunk API instead of List
  • All methods in the ItemWriteListener interface were updated to use the Chunk API instead of List
  • All implementations of ItemWriteListener were updated to use the Chunk API instead of List
  • The constructor of ChunkRequest was changed to accept a Chunk instead of a Collection of items
  • The return type of ChunkRequest#getItems() was changed from List to Chunk
  • The JobRepositoryTestUtils was changed to work against the JobRepository interface without depending on a datasource bean. For this change, the constructor that takes a DataSource as a parameter (JobRepositoryTestUtils(JobRepository jobRepository, DataSource dataSource)) as well as the public DataSource setter were removed. This is related to issue #4070.
  • The method StepBuilderHelper#transactionManager(PlatformTransactionManager) was moved to AbstractTaskletStepBuilder. This is related to issue https://github.com/spring-projects/spring-batch/issues/4130.
  • The methods RemotePartitioningManagerStepBuilder#transactionManager(PlatformTransactionManager) and RemotePartitioningWorkerStepBuilder#transactionManager(PlatformTransactionManager) were removed. A transaction manager is not required for those type of steps. This is related to issue https://github.com/spring-projects/spring-batch/issues/4130.
  • The method JobParameter#getType now returns T instead of Object
  • The constructors in JobParameter that took the 4 pre-defined job parameter types (date, string, long, double) where removed.
  • The constructor SkipWrapper(Throwable e) was removed
  • The setter setIsolationLevelForCreate(Isolation) in AbstractJobRepositoryFactoryBean was renamed to setIsolationLevelForCreateEnum
  • The return type of JobExplorer#getJobInstanceCount and JobInstanceDao#getJobInstanceCount has been changed from int to long
  • The return type of JobRepository#getStepExecutionCount and StepExecutionDao#countStepExecutions has been changed from int to long

(和訳)

さらに、以下のAPIが廃止されることなく削除/更新された:

org.springframework.batch.core.configuration.annotation.BatchConfigurer インターフェースが削除されました。https://github.com/spring-projects/spring-batch/issues/3942 を参照してください。
org.springframework.batch.core.configuration.annotation.DefaultBatchConfigurer クラスが削除されました。https://github.com/spring-projects/spring-batch/issues/3942 を参照。
org.springframework.batch.core.step.builder.SimpleStepBuilder#processor(Function) メソッドが削除され、項目プロセッサとしてラムダを渡せるようになった。この削除の根拠については https://github.com/spring-projects/spring-batch/issues/4061 を参照してください。SimpleStepBuilder::processorの引数として実際のFunctionを使用している場合、v5に移行するために.processor(function::apply)に変更することができます。

org.springframework.batch.item.data.builder.RepositoryItemReaderBuilder.RepositoryMethodReference という静的型と org.springframework.batch.item.data.builder.RepositoryItemReaderBuilder#repository(RepositoryMethodReference<? >) というメソッドが削除されました。
ItemWriter#write(List)メソッドのシグネチャがItemWriter#write(Chunk)に変更された。
ItemWriterのすべての実装が、Listの代わりにChunk APIを使用するように更新されました。
ItemWriteListenerインターフェイスのすべてのメソッドが、Listの代わりにChunk APIを使用するように更新されました。
ItemWriteListener のすべての実装が、List の代わりに Chunk API を使用するように更新されました。
ChunkRequest のコンストラクタは、アイテムの Collection の代わりに Chunk を受け入れるように変更されました。
ChunkRequest#getItems() の戻り値の型が List から Chunk に変更されました。
JobRepositoryTestUtils は、データソースビーンに依存せずに JobRepository インターフェースに対して動作するように変更されました。この変更に伴い、データソースをパラメータとして受け取るコンストラクタ(JobRepositoryTestUtils(JobRepository jobRepository, DataSource dataSource))とパブリックデータソースセッタが削除されました。これは issue #4070 に関連しています。

StepBuilderHelper#transactionManager(PlatformTransactionManager) は AbstractTaskletStepBuilder に移動されました。これは問題 https://github.com/spring-projects/spring-batch/issues/4130 に関連しています。
RemotePartitioningManagerStepBuilder#transactionManager(PlatformTransactionManager) および RemotePartitioningWorkerStepBuilder#transactionManager(PlatformTransactionManager) メソッドは削除されました。これらのタイプのステップでは、トランザクションマネージャは必要ありません。これは問題 https://github.com/spring-projects/spring-batch/issues/4130 に関連しています。
JobParameter#getType メソッドは Object ではなく T を返すようになりました。
JobParameterのコンストラクタで、事前に定義された4つのジョブパラメータ型(date、string、long、double)が削除されました。
コンストラクタSkipWrapper(Throwable e)が削除されました。
AbstractJobRepositoryFactoryBean のセッター setIsolationLevelForCreate(Isolation) は setIsolationLevelForCreateEnum に名前が変更されました。
JobExplorer#getJobInstanceCountとJobInstanceDao#getJobInstanceCountの戻り値の型がintからlongに変更されました。
JobRepository#getStepExecutionCountおよびStepExecutionDao#countStepExecutionsの戻り値の型がintからlongに変更されました。

 

<コメント>

・関連するクラスやメソッドをgrepして、該当したら、各理由を確認するのがよさそう。

 

Pruning

(和訳)

剪定

 

<コメント>

・サポート終了系

 

SQLFire support removal

SqlFire has been announced to be EOL as of November 1st, 2014. The support of SQLFire as a job repository was deprecated in version 4.3 and removed in version 5.0.

(和訳)

SQLFireサポート終了のお知らせ

SqlFireは2014年11月1日をもってEOLとなることが発表されました。SQLFireのジョブリポジトリとしてのサポートはバージョン4.3で廃止され、バージョン5.0で削除されました。

 

<コメント>

・削除されているので、使えない。

 

JSR-352 implementation removal

Due to a lack of adoption, the implementation of the JSR-352 has been discontinued in this release.

(和訳)

JSR-352実装の削除

JSR-352 の実装は、採用されなかったため、このリリースで廃止されました。

 

<コメント>

・関連する実装をしている場合は、SpringBatchを使えない?

 

Gemfire support removal

Based on the decision to discontinue the support of Spring Data for Apache Geode, the support for Geode in Spring Batch was removed. The code was moved to the spring-batch-extensions repository as a community-driven effort.

(和訳)

Gemfireサポートの廃止


Spring Data for Apache Geodeのサポート中止の決定に基づき、Spring BatchにおけるGeodeのサポートが削除された。コミュニティ主導の取り組みとして、コードはspring-batch-extensionsリポジトリに移動された。

 

<コメント>

・ユーザーのセッション管理に使われるライブラリの様子。リポジトリが変わるので、別途追加が必要になる?

 

最後に

意外と根本的な考え方の変更があるので、特にイレギュラーなことをやっている場合、今までできたことがそのままの形でできると思わないほうがよさそう。