java mongo 獲取所有數據庫_Spring Batch —從XML讀取并寫入Mongo

Java面試必備之JVM+GC教程

這幾天閑著在優銳課的java學習必備中學習了,在本文中,了解如何使用Spring Batch通過StaxEventItemReader使用ItemReader讀取XML文件并將其數據寫入NoSQL。

在本文中,我們將向展示如何使用Spring Batch使用StaxEventItemReader和ItemReader讀取XML文件,以及如何使用帶有JpaRepository的Custom ItemWriter將其數據寫入NoSQL。在這里,我們使用了MongoDB。

自定義ItemReader或ItemWriter是一個類,我們在其中編寫自己的讀取或寫入數據的方式。在Custom Reader中,我們也需要處理分塊邏輯。如果我們的讀取邏輯很復雜并且無法使用spring提供的Default ItemReader進行處理,那么這將很方便。

使用的工具和庫:

1. Maven 3.5+

2. Spring Batch Starter

3. Spring OXM

4. Data Mongodb starter

5. xstream

Maven依賴關系- 需要配置項目。

<?xml version="1.0" encoding="UTF-8"?>
<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 https://maven.apache.org/xsd/maven-4.0.0.xsd"><modelVersion>4.0.0</modelVersion><p><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-parent</artifactId><version>2.2.2.RELEASE</version><relativePath ></relativePath> <!-- lookup parent from repository --></parent><groupId>com.example</groupId><artifactId>spring-batch-mongodb</artifactId><version>0.0.1-SNAPSHOT</version><name>spring-batch-mongodb</name><description>Demo project for Spring Boot</description><p><java.version>1.8</java.version><maven-jar-plugin.version>3.1.1</maven-jar-plugin.version></properties><dependencies><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-batch</artifactId></dependency><dependency><groupId>org.springframework</groupId><artifactId>spring-oxm</artifactId></dependency><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-data-mongodb</artifactId></dependency><dependency><groupId>com.thoughtworks.xstream</groupId><artifactId>xstream</artifactId><version>1.4.7</version></dependency><dependency><groupId>org.projectlombok</groupId><artifactId>lombok</artifactId><optional>true</optional></dependency><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-test</artifactId><scope>test</scope><exclusions><exclusion><groupId>org.junit.vintage</groupId><artifactId>junit-vintage-engine</artifactId></exclusion></exclusions></dependency><dependency><groupId>org.springframework.batch</groupId><artifactId>spring-batch-test</artifactId><scope>test</scope></dependency><dependency><groupId>com.h2database</groupId><artifactId>h2</artifactId><scope>runtime</scope></dependency></dependencies><build><p><p><groupId>org.springframework.boot</groupId><artifactId>spring-boot-maven-plugin</artifactId></plugin></plugins></build>
</project>

CustomerWriter — 這是我們創建的自定義寫入器,用于將客戶數據寫入MongoDB。自定義編寫器也提供執行復雜操作的功能。

package com.example.writer;
import java.util.List;
import org.springframework.batch.item.ItemWriter;
import org.springframework.beans.factory.annotation.Autowired;
import com.example.domain.Customer;
import com.example.repository.CustomerRepository;
public class CustomerWriter implements ItemWriter<Customer>{@Autowiredprivate CustomerRepository customerRepository;@Overridepublic void write(List<? extends Customer> customers) throws Exception {customerRepository.saveAll(customers);}
}

CustomerRepository — 這是一個Mongo存儲庫,可與Mongo數據庫進行對話并執行操作以取回數據。

package com.example.repository;
import org.springframework.data.mongodb.repository.MongoRepository;
import com.example.domain.Customer;
public interface CustomerRepository extends MongoRepository<Customer, String>{
}

客戶 —這是一個包含業務數據的Mongo文檔類。

package com.example.domain;
import java.time.LocalDate;
import javax.xml.bind.annotation.XmlRootElement;
import org.springframework.data.annotation.Id;
import org.springframework.data.mongodb.core.mapping.Document;
import org.springframework.data.mongodb.core.mapping.Field;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
@AllArgsConstructor
@NoArgsConstructor
@Builder
@Data
@XmlRootElement(name = "Customer")
@Document
public class Customer {@Idprivate Long id;@Fieldprivate String firstName;@Fieldprivate String lastName;@Fieldprivate LocalDate birthdate;
}

CustomerConverter — 我們已經實現了Converter接口。此類用于Converter實現,并且負責將Java對象與文本數據進行編組。如果在處理期間發生異常,則應引發ConversionException。如果使用高級com.thoughtworks.xstream.XStream門面,則可以使用XStream.registerConverter()方法注冊新的轉換器。

package com.example.config;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import com.example.domain.Customer;
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 CustomerConverter implements Converter {private static final DateTimeFormatter DT_FORMATTER = DateTimeFormatter.ofPattern("dd-MM-yyyy HH:mm:ss");@Overridepublic boolean canConvert(Class type) {return type.equals(Customer.class);}@Overridepublic void marshal(Object source, HierarchicalStreamWriter writer, MarshallingContext context) {// Don't do anything}@Overridepublic Object unmarshal(HierarchicalStreamReader reader, UnmarshallingContext context) {reader.moveDown();Customer customer = new Customer();customer.setId(Long.valueOf(reader.getValue()));reader.moveUp();reader.moveDown();customer.setFirstName(reader.getValue());reader.moveUp();reader.moveDown();customer.setLastName(reader.getValue());reader.moveUp();reader.moveDown();customer.setBirthdate(LocalDate.parse(reader.getValue(), DT_FORMATTER));return customer;}
}

JobConfiguration- 這是負責執行批處理作業的主要類。在此類中,我們使用了各種Bean來執行單獨的任務。

StaxEventItemReader — 用于讀取基于StAX的XML輸入的項目讀取器。它從輸入的XML文檔中提取片段,該片段對應于要處理的記錄。片段用StartDocument和EndDocument事件包裝,以便可以像獨立XML文檔一樣對片段進行進一步處理。該實現不是線程安全的。

CustomerWriter —這是一個自定義類,可將數據寫入MongoDB。

step1 —此步驟配置ItemReader和ItemWriter,但是ItemProcessor是可選步驟,我們已跳過。

作業- 代表作業的批處理域對象。Job是一個顯式抽象,表示開發人員指定的作業配置。應當注意,重新啟動策略是整體上應用的,而不是步驟。

package com.example.config;
import java.util.HashMap;
import java.util.Map;
import org.springframework.batch.core.Job;
import org.springframework.batch.core.Step;
import org.springframework.batch.core.configuration.annotation.JobBuilderFactory;
import org.springframework.batch.core.configuration.annotation.StepBuilderFactory;
import org.springframework.batch.item.xml.StaxEventItemReader;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.ClassPathResource;
import org.springframework.oxm.xstream.XStreamMarshaller;
import com.example.domain.Customer;
import com.example.writer.CustomerWriter;
@Configuration
public class JobConfiguration {@Autowiredprivate JobBuilderFactory jobBuilderFactory;@Autowiredprivate StepBuilderFactory stepBuilderFactory;@Beanpublic StaxEventItemReader<Customer> customerItemReader(){Map<String, Class> aliases = new HashMap<>();aliases.put("customer", Customer.class);CustomerConverter converter = new CustomerConverter();XStreamMarshaller ummarshaller = new XStreamMarshaller();ummarshaller.setAliases(aliases);ummarshaller.setConverters(converter);StaxEventItemReader<Customer> reader = new StaxEventItemReader<>();reader.setResource(new ClassPathResource("/data/customer.xml"));reader.setFragmentRootElementName("customer")reader.setUnmarshaller(ummarshaller);return reader;}@Beanpublic CustomerWriter customerWriter() {return new CustomerWriter();}@Beanpublic Step step1() throws Exception {return stepBuilderFactory.get("step1").<Customer, Customer>chunk(200).reader(customerItemReader()).writer(customerWriter()).build();}@Beanpublic Job job() throws Exception {return jobBuilderFactory.get("job").start(step1()).build();}
}

application.properties

spring.data.mongodb.host=localhost

spring.data.mongodb.port=27017

Customer.xml —這是Spring Batch讀取的示例數據。

<?xml version="1.0" encoding="UTF-8" ?>
<customers><customer><id>1</id><firstName>John</firstName><lastName>Doe</lastName><birthdate>10-10-1988 19:43:23</birthdate></customer><customer><id>2</id><firstName>James</firstName><lastName>Moss</lastName><birthdate>01-04-1991 10:20:23</birthdate></customer><customer><id>3</id><firstName>Jonie</firstName><lastName>Gamble</lastName><birthdate>21-07-1982 11:12:13</birthdate></customer><customer><id>4</id><firstName>Mary</firstName><lastName>Kline</lastName><birthdate>07-08-1973 11:27:42</birthdate></customer><customer><id>5</id><firstName>William</firstName><lastName>Lockhart</lastName><birthdate>04-04-1994 04:15:11</birthdate></customer><customer><id>6</id><firstName>John</firstName><lastName>Doe</lastName><birthdate>10-10-1988 19:43:23</birthdate></customer><customer><id>7</id><firstName>Kristi</firstName><lastName>Dukes</lastName><birthdate>17-09-1983 21:22:23</birthdate></customer><customer><id>8</id><firstName>Angel</firstName><lastName>Porter</lastName><birthdate>15-12-1980 18:09:09</birthdate></customer><customer><id>9</id><firstName>Mary</firstName><lastName>Johnston</lastName><birthdate>07-07-1987 19:43:03</birthdate></customer><customer><id>10</id><firstName>Linda</firstName><lastName>Rodriguez</lastName><birthdate>16-09-1991 09:13:43</birthdate></customer><customer><id>11</id><firstName>Phillip</firstName><lastName>Lopez</lastName><birthdate>18-12-1965 11:10:09</birthdate></customer><customer><id>12</id><firstName>Peter</firstName><lastName>Dixon</lastName><birthdate>09-05-1996 19:09:23</birthdate></customer>
</customers>

MainApp — SpringBatchMongodbApplication可以作為Spring Boot項目運行。

package com.example;

import org.springframework.batch.core.configuration.annotation.EnableBatchProcessing;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration;
import org.springframework.data.mongodb.repository.config.EnableMongoRepositories;
@SpringBootApplication(exclude = {DataSourceAutoConfiguration.class})
@EnableBatchProcessing
@EnableMongoRepositories(basePackages = "com.example.repository")
public class SpringBatchMongodbApplication {public static void main(String[] args) {SpringApplication.run(SpringBatchMongodbApplication.class, args);}
}

輸出:我們可以得出結論,Spring Batch已經使用建議的模式/文檔類型讀取了數據并將其寫入MongoDB。

db.getCollection('customer').find({})
/* 1 */
{"_id" : NumberLong(1),"firstName" : "John","lastName" : "Doe","birthdate" : ISODate("1988-10-09T18:30:00.000Z"),"_class" : "com.example.domain.Customer"
}
/* 2 */
{"_id" : NumberLong(2),"firstName" : "James","lastName" : "Moss","birthdate" : ISODate("1991-03-31T18:30:00.000Z"),"_class" : "com.example.domain.Customer"
}
/* 3 */
{"_id" : NumberLong(3),"firstName" : "Jonie","lastName" : "Gamble","birthdate" : ISODate("1982-07-20T18:30:00.000Z"),"_class" : "com.example.domain.Customer"
}
/* 4 */
{"_id" : NumberLong(4),"firstName" : "Mary","lastName" : "Kline","birthdate" : ISODate("1973-08-06T18:30:00.000Z"),"_class" : "com.example.domain.Customer"
}
/* 5 */
{"_id" : NumberLong(5),"firstName" : "William","lastName" : "Lockhart","birthdate" : ISODate("1994-04-03T18:30:00.000Z"),"_class" : "com.example.domain.Customer"
}
/* 6 */
{"_id" : NumberLong(6),"firstName" : "John","lastName" : "Doe","birthdate" : ISODate("1988-10-09T18:30:00.000Z"),"_class" : "com.example.domain.Customer"
}
/* 7 */
{"_id" : NumberLong(7),"firstName" : "Kristi","lastName" : "Dukes","birthdate" : ISODate("1983-09-16T18:30:00.000Z"),"_class" : "com.example.domain.Customer"
}
/* 8 */
{"_id" : NumberLong(8),"firstName" : "Angel","lastName" : "Porter","birthdate" : ISODate("1980-12-14T18:30:00.000Z"),"_class" : "com.example.domain.Customer"
}
/* 9 */
{"_id" : NumberLong(9),"firstName" : "Mary","lastName" : "Johnston","birthdate" : ISODate("1987-07-06T18:30:00.000Z"),"_class" : "com.example.domain.Customer"
}
/* 10 */
{"_id" : NumberLong(10),"firstName" : "Linda","lastName" : "Rodriguez","birthdate" : ISODate("1991-09-15T18:30:00.000Z"),"_class" : "com.example.domain.Customer"
}
/* 11 */
{"_id" : NumberLong(11),"firstName" : "Phillip","lastName" : "Lopez","birthdate" : ISODate("1965-12-17T18:30:00.000Z"),"_class" : "com.example.domain.Customer"
}
/* 12 */
{"_id" : NumberLong(12),"firstName" : "Peter","lastName" : "Dixon","birthdate" : ISODate("1996-05-08T18:30:00.000Z"),"_class" : "com.example.domain.Customer"
}

> 喜歡這篇文章的可以點個贊,歡迎大家留言評論,記得關注我,每天持續更新技術干貨、職場趣事、海量面試資料等等

> 如果你對java技術很感興趣也可以交流學習,共同學習進步。

> 不要再用"沒有時間“來掩飾自己思想上的懶惰!趁年輕,使勁拼,給未來的自己一個交代

文章寫道這里,歡迎完善交流。最后奉上近期整理出來的一套完整的java架構思維導圖,分享給大家對照知識點參考學習。有更多JVM、Mysql、Tomcat、Spring Boot、Spring Cloud、Zookeeper、Kafka、RabbitMQ、RockerMQ、Redis、ELK、Git等Java干貨

fbcae7c1b51d2fbb3c66cdb28631c4a4.png

本文來自互聯網用戶投稿,該文觀點僅代表作者本人,不代表本站立場。本站僅提供信息存儲空間服務,不擁有所有權,不承擔相關法律責任。
如若轉載,請注明出處:http://www.pswp.cn/news/273244.shtml
繁體地址,請注明出處:http://hk.pswp.cn/news/273244.shtml
英文地址,請注明出處:http://en.pswp.cn/news/273244.shtml

如若內容造成侵權/違法違規/事實不符,請聯系多彩編程網進行投訴反饋email:809451989@qq.com,一經查實,立即刪除!

相關文章

001多表查詢.交叉鏈接cross JOIN.自然鏈接natural JOIN.using鏈接.on鏈接

-- 需求&#xff1a;查詢每一個員工信息&#xff0c;并且顯示每一個員工所在的部門名稱 -- mysql中多表查詢有四種&#xff0c;交叉鏈接cross JOIN&#xff0c;自然鏈接natural JOIN&#xff0c;using鏈接&#xff0c;on鏈接 -- 交叉鏈接cross JOIN SELECT * FROM emp; --6…

poj1969---找規律

題意&#xff1a;按照s型分別給數編號&#xff0c;給 #include <stdio.h> #include <stdlib.h>int main() {int n;while(scanf("%d",&n) ! EOF){int s0,k1;while(1){sk;//統計個數&#xff0c;當前幾斜線和大于了規定的序號&#xff0c;說明此時該數…

華菱重卡儀表指示說明_新一代創虎重卡登場!LNG車型將配玉柴燃氣發動機

2020年10月23日&#xff0c;現代商用車新一代創虎重卡正式發布&#xff0c;此次新車不僅外觀與韓國本土同步&#xff0c;更是首次搭載了國產玉柴動力&#xff0c;推出了LNG版車型。具體情況我們先搶先看看吧&#xff01;外觀升級 與韓國本土同步我們可以看到&#xff0c;相比此…

mysql002多表查詢.on鏈接分為三種情況,左鏈接,右鏈接,全鏈接

-- on鏈接&#xff08;最實用&#xff09;&#xff0c;分為三種情況&#xff0c;左鏈接&#xff0c;右鏈接&#xff0c;全鏈接 -- 左外鏈接&#xff0c;左表全部顯示&#xff0c;如果匹配不到右表的內容使用null代替。 SELECT * FROM emp e LEFT JOIN dept d ON e.DEPTNOd.DE…

x軸z軸代表的方向圖片_游戲中到底是Z軸朝上還是Y軸朝上?

本文轉自我的公眾號——游戲開發那些事在談到游戲世界中的坐標軸時&#xff0c;我們經常會看到這樣的爭論。“游戲中Y軸是向上的好么&#xff1f;這你都不知道&#xff1f;”“不對&#xff0c;空間直角坐標系不就是Z軸向上的么&#xff1f;”“拜托&#xff0c;請搞清楚坐標系…

補發《超級迷宮》站立會議三

那天我給自己的任務是實現控件的控制&#xff0c;但結果明顯很不理想&#xff0c;我僅僅加載了兩個控件&#xff08;即兩個小人&#xff09;&#xff0c;一個是玩家&#xff0c;另一個是守關者&#xff0c;玩家控制基本實現&#xff0c;通過方向鍵進行控制&#xff1b;但守關者…

mysql003三表查詢.三表查詢.自鏈接查詢

-- 多表查詢 三表查詢 -- 查詢員工的編號&#xff0c;姓名&#xff0c;薪水&#xff0c;部門編號&#xff0c;部門名稱&#xff0c;薪水等級 -- 可以先兩表查詢&#xff0c;在修改成三表查詢 -- 第一行查詢的內容&#xff0c;第二,三行查詢需要的表&#xff0c; -- 和條件…

[轉]jQuery源碼分析系列

文章轉自&#xff1a;jQuery源碼分析系列-Aaron 版本截止到2013.8.24 jQuery官方發布最新的的2.0.3為準 附上每一章的源碼注釋分析 &#xff1a;https://github.com/JsAaron/jQuery 正在編寫的書 - jQuery架構設計與實現 本人在慕課網的教程&#xff08;完結&#xff09; jQue…

hook xposed 自定義類_【開始學習React Hook(1)】Hook之useState

react hook是react推出的一種特殊函數。這些函數可以讓你在不創建react class的情況下依然可以使用react的一些特性&#xff08;諸如目前react的鉤子函數擁有的所有特性&#xff09;。最常用的hook有useState, useEffect, 日常開發使用這兩個就足夠了。如果再懂點useReduer, us…

mysql004子查詢.相關子查詢.不相關子查詢

子查詢&#xff1a;相關子查詢&#xff0c;不相關子查詢 -- 不相關子查詢 -- 一條SQL語句含有多個select,先執行子查詢&#xff0c;在執行外部查詢。子查詢可以獨立運行&#xff0c;成為不相關子查詢。 -- 需求1&#xff1a;查詢所有比姓名為“CLARK”工資高的員工的信息。 …

文件無刷新上傳(swfUpload與uploadify)

文件無刷新上傳并獲取保存到服務器端的路徑 遇到上傳文件的問題&#xff0c;結合之前用到過的swfUpload&#xff0c;又找了一個無刷新上傳文件的jquery插件uploadify&#xff0c;寫篇博客記錄一下分別介紹這兩個插件的實現方法 swfUpload 導入swfUpload的開發包 添加js引用&am…

ediplus 復制編輯一列_vi編輯器的使用詳解

一個編輯器具備的功能一個編輯器(例如Windows中的記事本)具備的功能&#xff1a;打開文件、新建文件、保存文件光標移動文本編輯(多行間|多列間)復制、粘貼、刪除查找和替換vi編輯器的環境設置為了更方便的使用vi編輯器&#xff0c;我們需要先對vi編輯器進行一些配置。打開虛擬…

myjdbc鏈接數據庫.增刪改查

-- 創建user表 CREATE TABLE user( uid int PRIMARY KEY auto_increment, uname VARCHAR(55), pwd VARCHAR(55), realName VARCHAR(55) ) SELECT * FROM user; Jdbc增刪改查 package myjdbc; import java.sql.Connection; import java.sql.DriverManager; import java.…

JAVA中通過時間格式來生成唯一的文件名

有時候我們需要截圖&#xff0c;在要截圖時&#xff0c;有人用到了時間格式&#xff0c;但是時間格式中的:在文件名稱中是不被允許的字符&#xff0c;所以就會報錯&#xff0c;如何生成唯一的時間文件名&#xff1a; package com.demo;import java.text.ParseException; import…

python返回字符串長度的函數_Python如何查找字符串的長度?(代碼示例)

在Python中字符串是Unicode代碼點的不可變序列。給定一個字符串&#xff0c;我們如何查找它的長度&#xff1f;本篇文章就來給大家介紹在Python中查找字符串長度的四種方法&#xff0c;希望對大家有所幫助。【相關視頻教程推薦&#xff1a;Python視頻教程】方法一&#xff1a;使…

K-means算法和矢量量化

語音信號的數字處理課程作業——矢量量化。這里采用了K-means算法&#xff0c;即假設量化種類是已知的&#xff0c;當然也可以采用LBG算法等&#xff0c;不過K-means比較簡單。矢量是二維的&#xff0c;可以在平面上清楚的表示出來。 1. 算法描述 本次實驗選擇了K-means算法對數…

docker 主進程 日志_運維筆記--docker高效查看后臺日志

場景描述&#xff1a;應用程序運行在 Docker環境中&#xff0c;經常使用的查看后臺日志的命令是&#xff1a;docker attach 容器名該命令優點&#xff1a;實時輸出&#xff1b;不足之處&#xff1a;日志大量輸出的時候&#xff0c;屏幕一閃而過&#xff0c;不便于調試&#xff…

jdbc.properties文件

drivercom.mysql.cj.jdbc.Driver (//主機&#xff1a;端口號、數據庫名)urljdbc:mysql://localhost:3306/mydb?useSSLfalse&useUnicodetrue&characterEncodingutf8&serverTimezoneAsia/Shanghaiusername(鏈接的用戶)passwd(密碼)

ifix如何設畫面大小_如何讓你的視頻又小又清晰?視頻編碼輸出軟件來了

如何讓視頻保持清晰同時又讓其體積盡可能的小&#xff1f;這是很多小伙伴們都很頭疼的問題而且很多時候我們需要會在微信或者朋友圈等社交平臺上傳我們的作品但它們對視頻大小有著比較嚴格的控制所以蜜蜂菌就為大家帶來了視頻壓縮神器小丸工具箱幫助你輕松壓縮出又小又清晰的視…

智能集群理論優化控制_探索群體智能的奧妙——ROB-MAS多智能體協作

人類對未知領域總是充滿好奇和敬畏。因為好奇&#xff0c;所以不斷探索&#xff0c;因為敬畏&#xff0c;所以小心謹慎。談到人工智能&#xff0c;已經不僅僅是停留在智能手機、家用電器這個層次&#xff0c;要知道&#xff0c;人工智能的作用&#xff0c;不僅僅是為了方便生活…