開発者ドキュメント

春バッチの例 – MySQLデータベースへのCSVファイル

このチュートリアルでは、CSVファイルからデータベースにデータを読み込むためにSpringバッチジョブを設定する方法を説明します。

使用されるツールとライブラリ:

  1. Maven 3

  2. Eclipse 4.2

  3. JDK 1.6

  4. Spring Core 3.2.2.RELEASE

  5. Spring Batch 2.2.0.RELEASE

  6. MySQLのJavaドライバ5.1.25

1. Javaプロジェクト

Mavenを使ってJavaプロジェクトを作成する

$ mvn archetype:generate -DgroupId=com.mkyong -DartifactId=SpringBatchExample
  -DarchetypeArtifactId=maven-archetype-quickstart -DinteractiveMode=false

Eclipseプロジェクトに変換し、Eclipse IDEにインポートします。

$ cd SpringBatchExample/$ mvn eclipse:eclipse

プロジェクトの依存関係


pom.xml

のすべてのプロジェクト依存関係を宣言します。

pom.xml

<project xmlns="http://maven.apache.org/POM/4.0.0"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0
    http://maven.apache.org/maven-v4__0__0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <groupId>com.mkyong</groupId>
    <artifactId>SpringBatchExample</artifactId>
    <packaging>jar</packaging>
    <version>1.0-SNAPSHOT</version>
    <name>SpringBatchExample</name>
    <url>http://maven.apache.org</url>

    <properties>
        <jdk.version>1.6</jdk.version>
        <spring.version>3.2.2.RELEASE</spring.version>
        <spring.batch.version>2.2.0.RELEASE</spring.batch.version>
        <mysql.driver.version>5.1.25</mysql.driver.version>
    </properties>

    <dependencies>

        <!-- Spring Core -->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-core</artifactId>
            <version>${spring.version}</version>
        </dependency>

        <!-- Spring jdbc, for database -->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-jdbc</artifactId>
            <version>${spring.version}</version>
        </dependency>

        <!-- Spring Batch dependencies -->
        <dependency>
            <groupId>org.springframework.batch</groupId>
            <artifactId>spring-batch-core</artifactId>
            <version>${spring.batch.version}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework.batch</groupId>
            <artifactId>spring-batch-infrastructure</artifactId>
            <version>${spring.batch.version}</version>
        </dependency>

        <!-- MySQL database driver -->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>${mysql.driver.version}</version>
        </dependency>

    </dependencies>
    <build>
        <finalName>spring-batch</finalName>
        <plugins>
          <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-eclipse-plugin</artifactId>
            <version>2.9</version>
            <configuration>
                <downloadSources>true</downloadSources>
                <downloadJavadocs>false</downloadJavadocs>
            </configuration>
          </plugin>
          <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-compiler-plugin</artifactId>
            <version>2.3.2</version>
            <configuration>
                <source>${jdk.version}</source>
                <target>${jdk.version}</target>
            </configuration>
          </plugin>
        </plugins>
    </build>
</project>

3.プロジェクトのディレクトリ構造

最終的なプロジェクトの構造を見直します。



4. CSVファイル

これはリソースフォルダのcsvファイルです。

report.csv

Date,Impressions,Clicks,Earning
6/1/13,"139,237",37,227.21
6/2/13,"149,582",55,234.71
6/3/13,"457,425",132,211.48
6/4/13,"466,870",141,298.40
6/5/13,"472,385",194,281.35
......

5. MySQL Database

Defines a “dataSource” bean for MySQL database. The

jdbc:initialize-database

is used to create the metadata tables
automatically, Spring Batch need it to store the job’s detail.

resources/spring/batch/config/database.xml

<beans xmlns = "http://www.springframework.org/schema/beans" xmlns:jdbc = "http://www.springframework.org/schema/jdbc" xmlns:xsi = "http://www.w3 .org/2001/XMLSchema-instance "xsi:schemaLocation =" http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.2.xsd http://www.springframework.org/schema/jdbc http://www.springframework.org/schema/jdbc/spring-jdbc-3.2.xsd ">

<! -  connect to database  - > <bean id = "dataSource" class = "org.springframework.jdbc.datasource.DriverManagerDataSource"> <プロパティ名= "driverClassName" value = "com.mysql.jdbc.Driver"/プロパティ名= "パスワード"値= "" <プロパティ名= "URL"値= "jdbc://ローカルホスト:3306/テスト"/>/> </bean>

<bean id = "transactionManager" class = "org.springframework.batch.support.transaction.ResourcelessTransactionManager"/> <! - ジョブ・メタ・テーブルを自動的に作成する>  -  <jdbc:initialize-database data-source = "dataSource" > <jdbc:スクリプトの場所= "org/springframework/batch/core/schema-mysql.sql"/> <jdbc:/jdbc:initialize-database>

</beans>

6.バネバッチコア設定


jobRepository`と

jobLauncher`を定義します。

resources/spring/batch/config/context.xml

<beans xmlns = "http://www.springframework.org/schema/beans" xmlns:xsi = "http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation = "http://www .springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.2.xsd ">

<! - データベースのストアド・ジョブ・メタデータ - > <bean id = "jobRepository" class = "org.springframework.batch.core.repository.support.JobRepositoryFactoryBean"> <property name = "dataSource" ref = "dataSource"/> <property name = "transactionManager" ref = "transactionManager"/> <property name = "databaseType" value = "mysql"/> </bean>

<! - ストアド・ジョブ・メタデータをメモリに格納する - > <! -  <bean id = "jobRepository" class = "org.springframework.batch.core.repository.support.MapJobRepositoryFactoryBean"> <property name = "transactionManager" ref <bean id = "jobLauncher" class = "org.springframework.batch.core.launch.support.SimpleJobLauncher"> <プロパティ名= "jobRepository" ref = "jobRepository"/> </bean>

</beans>

7.バッチバッチジョブ

これは、Springバッチジョブを設定するための主要なxmlファイルです。この

job-report.xml`ファイルは、

report.csv`ファイルを読み込んでそれにマッチさせるジョブを定義します
プレーンなpojoを `報告する ‘こと、そしてMySQLデータベースにデータを書き込むこと。

コメントを読む、それは自明でなければならない。 Btw、作成を覚えています


RAW__REPORT

“テーブルを手動で作成します。

resources/spring/batch/jobs/job-report.xml

<beans xmlns = "http://www.springframework.org/schema/beans" xmlns:batch = "http://www.springframework.org/schema/batch" xmlns:task = "http://www.springframework .org/schema/task "xmlns:xsi =" http://www.w3.org/2001/XMLSchema-instance "xsi:schemaLocation =" http://www.springframework.org/schema/batch http://www.springframework.org/schema/batch/spring-batch-2.2.xsd http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.2。 xsd ">

<batch id = "reportJob"> <batch:step id = "step1"> <batch id: "report" class = "com.mkyong.model.Report" scope = "プロトタイプ"/> </batch:tasklet> </batch:step> </batch:job> <バッチ:チャンクリーダー>「cvsFileItemReader」writer = "mysqlItemWriter"コミット間隔= "2"

<bean id = "cvsFileItemReader" class = "org.springframework.batch.item.file.FlatFileItemReader">

<! -  csvファイルを読み込みます - > <property name = "resource" value = "classpath:cvs/report.csv"/>

<property name = "lineMarker"> <bean class = "org.springframework.batch.item.file.mapping.DefaultLineMapper"> <! - 分割する - > <property name = "lineTokenizer"> <bean class = " </bean> </property> <property name = "fieldSetMapper">プロパティ名= "名前" value = "日付、印象、クリック、収益"/> </bean> > <! - マップされたオブジェクトではなく、リーダーに戻ります。 - > <! -  <bean class = "org.springframework.batch.item.file.mapping.PassThroughFieldSetMapper"/>  - > <! - オブジェクトにマップする - > <bean class = "org.springframework .batch.item.file.mapping.BeanWrapperFieldSetMapper "> <property name =" prototypeBeanName "value =" report "/> </bean> </property>

</bean> </property>

</bean>

<bean id = "mysqlItemWriter" class = "org.springframework.batch.item.database.JdbcBatchItemWriter"> <プロパティ名= "データソース" ref = "データソース"/> <プロパティ名= "sql"> <値> <![CDATA[日付、印象、CLICKS、EARNING]値(:日付、:印象、:クリック、収入)]]> </value> </property> <! - これは、オブジェクトプロパティとsql nameパラメータ - > <property name = "itemSqlParameterSourceProvider"> <bean class = "org.springframework.batch.item.database.BeanPropertyItemSqlParameterSourceProvider"/> </property> </bean>

</beans>

com/mkyong/model/Report.java

パッケージcom.mkyong.model;

public class Report {

プライベートString Date;プライベートストリングの印象;プライベートストリングクリック。プライベートストーリー獲得;//getterメソッドとsetterメソッド

}

8.それを実行する

すべてを読み込み、 `jobLauncher`を実行します。これは最も簡単な方法です
それを開始してテストしますが、実際には、
Springタスク、Quartzまたはシステムスケジューラのようなスケジューラフレームワーク
“cron”コマンド(次のチュートリアルで紹介します)。

com/mkyong/App.java

パッケージcom.mkyong;

import org.springframework.batch.core.Job;インポートorg.springframework.batch.core.JobExecution; org.springframework.batch.core.JobParametersをインポートします。 org.springframework.batch.core.launch.JobLauncherをインポートします。インポートorg.springframework.context.ApplicationContext;インポートorg.springframework.context.support.ClassPathXmlApplicationContext;

パブリッククラスApp {public static void main(String[]args){

[spring/batch/config/database.xml "、" spring/batch/config/context.xml "、" spring/batch/jobs/job-report.xml "}; ApplicationContext context =新しいClassPathXmlApplicationContext(springConfig); JobLauncher jobLauncher =(JobLauncher)context.getBean( "jobLauncher");ジョブジョブ=(ジョブ)context.getBean( "reportJob");

試して{

ジョブ実行の実行= jobLauncher.run(job、new JobParameters()); System.out.println( "終了ステータス:" execution.getStatus());

} catch(例外e){e.printStackTrace();} }

System.out.println( "Done");

}
}

出力。 Springバッチメタデータテーブルが作成され、
`report.cvs`はデータベーステーブル”

RAW__REPORT

“に挿入されます。




完了しました。

===ソースコードをダウンロードする

それをダウンロードする –

SpringBatch-CSV-Database-Example.zip

(18kb)

===参考文献

モバイルバージョンを終了