SpringBatchの例-XMLファイルからMongoDBデータベースへ
Spring Batch Example Xml File Mongodb Database
このチュートリアルでは、XMLファイルからデータを削除するようにSpring Batchジョブを構成する方法を示します( XStream ライブラリ)SQLなしでデータベースに読み込まれます( MongoDB )に。 さらに、バッチジョブを開始してテストするための単体テストケースを作成します。
使用したツールとライブラリ
- Maven 3
- Eclipse 4.2
- JDK 1.6
- Spring Core3.2.2。リリース
- Spring Batch2.2.0。リリース
- SpringBatchテスト2.2.0.RELEASE
- Spring OXM3.2.2。リリース
- MongoDBJavaドライバー2.11.2
- MongoDB 2.2.3
- JUnit 4.11
- 6.8.5のテスト
PSこの例-XMLファイル(リーダー)-MongoDB(ライター)。
1.単純なJavaプロジェクト
1. Mavenを使用してクイックスタートJavaプロジェクトを作成し、変換してEclipseIDEにインポートします。
$ mvn archetype:generate -DgroupId=com.mkyong -DartifactId=SpringBatchExample2 -DarchetypeArtifactId=maven-archetype-quickstart -DinteractiveMode=false
$ cd SpringBatchExample/ $ mvn eclipse:eclipse
2.プロジェクトの依存関係
in pom.xml
すべてのプロジェクトの依存関係を宣言する
4.0.0 com.mkyong SpringBatchExample jar 1.0-SNAPSHOT SpringBatchExample http://maven.apache.org 1.6 3.2.2.RELEASE 2.2.0.RELEASE 1.2.1.RELEASE 2.11.2 org.springframework spring-core ${spring.version} org.springframework spring-oxm ${spring.version} org.springframework.batch spring-batch-core ${spring.batch.version} org.springframework.batch spring-batch-infrastructure ${spring.batch.version} org.springframework.batch spring-batch-test ${spring.batch.version} org.mongodb mongo-java-driver ${mongodb.driver.version} org.springframework.data spring-data-mongodb ${spring.data.version} junit junit 4.11 test org.testng testng 6.8.5 test spring-batch org.apache.maven.plugins maven-eclipse-plugin 2.9 true false org.apache.maven.plugins maven-compiler-plugin 2.3.2 ${jdk.version} ${jdk.version}
3.プロジェクトのディレクトリ構造
次のステップの概要については、最終的なプロジェクト構造を参照してください。
4.XMLファイル
これは、リソースフォルダー内のXMLファイルです。
resources / xml / report.xml
6/1/2013 139,237 40 220.90 6/2/2013 339,100 60 320.88 6/3/2013 431,436 76 270.80
5.XMLファイルを読み取ります
Springバッチ処理では、StaxEventItemReader
XMLファイルを読み取り、XStreamMarshaller
XML値と属性をオブジェクトにマップすることができます。
package com.mkyong.model import java.math.BigDecimal import java.text.SimpleDateFormat import java.util.Date public class Report { private int id private Date date private long impression private int clicks private BigDecimal earning //getter and setter methods }
Report.java Date
XML値をBigDecimal
with converter
クラスの「複雑な」データ型にマップするには、カスタムを添付する必要がありますpackage com.mkyong.converter import java.math.BigDecimal import java.text.NumberFormat import java.text.ParseException import java.text.SimpleDateFormat import java.util.Date import java.util.Locale import com.mkyong.model.Report import com.thoughtworks.xstream.converters.Converter import com.thoughtworks.xstream.converters.MarshallingContext import com.thoughtworks.xstream.converters.UnmarshallingContext import com.thoughtworks.xstream.io.HierarchicalStreamReader import com.thoughtworks.xstream.io.HierarchicalStreamWriter public class ReportConverter implements Converter { @Override public boolean canConvert(Class type) { //we only need 'Report' object return type.equals(Report.class) } @Override public void marshal(Object source, HierarchicalStreamWriter writer, MarshallingContext context) { //do nothing } @Override public Object unmarshal( HierarchicalStreamReader reader, UnmarshallingContext context) { Report obj = new Report() //get attribute obj.setId(Integer.valueOf(reader.getAttribute('id'))) reader.moveDown() //get date Date date = null try { date = new SimpleDateFormat('M/d/yyyy').parse(reader.getValue()) } catch (ParseException e) { e.printStackTrace() } obj.setDate(date) reader.moveUp() reader.moveDown() //get impression String impression = reader.getValue() NumberFormat format = NumberFormat.getInstance(Locale.US) Number number = 0 try { number = format.parse(impression) } catch (ParseException e) { e.printStackTrace() } obj.setImpression(number.longValue()) reader.moveUp() reader.moveDown() //get click obj.setClicks(Integer.valueOf(reader.getValue())) reader.moveUp() reader.moveDown() //get earning obj.setEarning(new BigDecimal(reader.getValue())) reader.moveUp() return obj } }
値を手動で変換してマップします。
mongoTemplate
6.MongoDBデータベース
mongodbインスタンスを定義し、a jobRepository
。
jobLauncher
7. SpringBatchコア設定
定義report.xml
with Report
。
MongoDB
8.春のバッチジョブ
Springバッチジョブ、読み取り //write it to MongoDB, 'report' collection (table)
ファイル、マップJobLauncherTestUtils
オブジェクトと書き込みpackage com.mkyong import static org.junit.Assert.assertEquals import org.junit.Test import org.junit.runner.RunWith import org.springframework.batch.core.BatchStatus import org.springframework.batch.core.JobExecution import org.springframework.batch.test.JobLauncherTestUtils import org.springframework.beans.factory.annotation.Autowired import org.springframework.test.context.ContextConfiguration import org.springframework.test.context.junit4.SpringJUnit4ClassRunner @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration(locations = { 'classpath:spring/batch/jobs/job-report.xml', 'classpath:spring/batch/config/context.xml', 'classpath:spring/batch/config/database.xml', 'classpath:spring/batch/config/test-context.xml'}) public class AppTest { @Autowired private JobLauncherTestUtils jobLauncherTestUtils @Test public void launchJob() throws Exception { //JobExecution jobExecution = jobLauncherTestUtils.launchJob() JobExecution jobExecution = jobLauncherTestUtils.launchStep('step1') assertEquals(BatchStatus.COMPLETED, jobExecution.getStatus()) } }
。 レビューを読んでください、それは自明であるはずです。
package com.mkyong import org.springframework.batch.core.BatchStatus import org.springframework.batch.core.JobExecution import org.springframework.batch.test.JobLauncherTestUtils import org.springframework.beans.factory.annotation.Autowired import org.springframework.test.context.ContextConfiguration import org.springframework.test.context.testng.AbstractTestNGSpringContextTests import org.testng.Assert import org.testng.annotations.Test @ContextConfiguration(locations = { 'classpath:spring/batch/jobs/job-report.xml', 'classpath:spring/batch/config/context.xml', 'classpath:spring/batch/config/database.xml', 'classpath:spring/batch/config/test-context.xml'}) public class AppTest2 extends AbstractTestNGSpringContextTests { @Autowired private JobLauncherTestUtils jobLauncherTestUtils @Test public void launchJob() throws Exception { JobExecution jobExecution = jobLauncherTestUtils.launchJob() Assert.assertEquals(jobExecution.getStatus(), BatchStatus.COMPLETED) } }
9.ユニットテスト
jUnitまたはTestNGフレームワークを使用してユニットテストを行います。まず、手動で宣言する必要がありますmongo MongoDB shell version: 2.2.3 connecting to: test > use yourdb switched to db yourdb > show collections report system.indexes > db.report.find() { '_id' : 1, '_class' : 'com.mkyong.model.Report', 'date' : ISODate('2013-05-31T16:00:00Z'), 'impression' : NumberLong(139237), 'clicks' : 40, 'earning' : '220.90' } { '_id' : 2, '_class' : 'com.mkyong.model.Report', 'date' : ISODate('2013-06-01T16:00:00Z'), 'impression' : NumberLong(339100), 'clicks' : 60, 'earning' : '320.88' } { '_id' : 3, '_class' : 'com.mkyong.model.Report', 'date' : ISODate('2013-06-02T16:00:00Z'), 'impression' : NumberLong(431436), 'clicks' : 76, 'earning' : '270.80' } >
。
|_+_|
jUnitの例
AppTest.java|_+_|
TestNGの例
AppTest2.java|_+_|
出力。 XML値がMongoDBに挿入されます。
|_+_|
10.ジョブのメタデータはどうですか?
申し訳ありませんが、まだ解決策はありません。 私の知る限り、ジョブのメタデータには、ジョブの再開可能性とロールバックを保証するためのリレーショナルデータベースが必要です。 設計上、MongoDBには「信頼できる」トランザクション管理がありません。
解決策1:ジョブのメタデータを格納する別のリレーショナルデータベースを作成します。ばかげているように聞こえますが、機能します。 もっといいアイデアはありますか?
解決策2:Springチームがこの解決策を考え出すのを待ちます。
ソースコードをダウンロードする
ダウンロード– SpringBatch-XML-MongoDB-Example.zip (81kb)参照
- XStreamコンバータチュートリアル
- 非RDBMSのSpringBatchサポート
- Spring BatchXMLアイテムリーダーおよびライター
- SpringBatch-ジョブを構成して実行する
- Mavenを使用してJavaプロジェクトを作成します
から: https://mkyong.com/spring-batch/spring-batch-example-xml-file-to-database/