Learn IT with Examples
Free tutorials with examples : learn IT & improve your IT skills. |
Site created by Paul Catalin Tomoiu Enterprise / Solution Architect |
The tutorial named 'Spring Batch: Write data to a H2 database' will explain how you can write some data to a database using Spring Batch. In my example I use the H2 database.
SPRING BATCH: Write data to a H2 database With Spring Batch, you can define and run jobs. The jobs may have a step or many steps.
Typically Batch Jobs are long-running, non-interactive and process large volumes of data, more than fits in memory or a single transaction. During a step, the job do something, a particular task, named tasklet. When you define a step you can define the next step you have to execute. A job could execute steps in a defined order.
When you define a step you have 2 models: 1) run a simple task (tasklet) 2) run a step using the following pattern READ-PROCESS-WRITE
This tutorial explains you how to use the second approach. The first model can be seen when you read the article named "SPRING BATCH: Create a Step".
We can have in Spring Batch: sequential steps and parallel steps. We can execute some tasks (steps) when a condition is true or false. Because of these things, you can create workflows using Spring Batch. For more information related to Spring Batch model you can take a look to the article named "SPRING BATCH: The Main Concepts".
In this tutorial you can see how you can read a CSV file and write the content into a H2 database all this in one step. This step follow the pattern READ-PROCESS-WRITE, but in this example I skip the "PROCESS" activity for creating a simpler example.
In order to create a simple example using the pattern READ-PROCESS-WRITE in Spring Batch, first you have to create a simple Maven Spring project with the pom.xml file having the following dependencies:
At this point it is supposed that the Job Repository has been configured already. Take a look at the article named "SPRING BATCH: Infrastructure Configuration (Using H2)".
In order to see how to create a READ-PROCESS_WRITE step, you have to create a batch.properties file with the following content :
and add the following classes: package com.examples.springbatch; import java.io.Serializable; public class UserRegistration implements Serializable { private static final long serialVersionUID = 1L; private String firstName; private String lastName; private String company; private String address; private String city; private String state; private String zip; private String county; private String url; private String phoneNumber; private String fax; public UserRegistration() { } public UserRegistration(String firstName, String lastName, String company, String address, String city, String state, String zip, String county, String url, String phoneNumber, String fax) { super(); this.firstName = firstName; this.lastName = lastName; this.company = company; this.address = address; this.city = city; this.state = state; this.zip = zip; this.county = county; this.url = url; this.phoneNumber = phoneNumber; this.fax = fax; } public String getFirstName() { return firstName; } public void setFirstName(String firstName) { this.firstName = firstName; } public String getLastName() { return lastName; } public void setLastName(String lastName) { this.lastName = lastName; } public String getCompany() { return company; } public void setCompany(String company) { this.company = company; } public String getAddress() { return address; } public void setAddress(String address) { this.address = address; } public String getCity() { return city; } public void setCity(String city) { this.city = city; } public String getState() { return state; } public void setState(String state) { this.state = state; } public String getZip() { return zip; } public void setZip(String zip) { this.zip = zip; } public String getCounty() { return county; } public void setCounty(String county) { this.county = county; } public String getUrl() { return url; } public void setUrl(String url) { this.url = url; } public String getPhoneNumber() { return phoneNumber; } public void setPhoneNumber(String phoneNumber) { this.phoneNumber = phoneNumber; } public String getFax() { return fax; } public void setFax(String fax) { this.fax = fax; } } package com.examples.springbatch; import java.io.Serializable; public class UserRegistration implements Serializable { private static final long serialVersionUID = 1L; private String firstName; private String lastName; private String company; private String address; private String city; private String state; private String zip; private String county; private String url; private String phoneNumber; private String fax; public UserRegistration() { } public UserRegistration(String firstName, String lastName, String company, String address, String city, String state, String zip, String county, String url, String phoneNumber, String fax) { super(); this.firstName = firstName; this.lastName = lastName; this.company = company; this.address = address; this.city = city; this.state = state; this.zip = zip; this.county = county; this.url = url; this.phoneNumber = phoneNumber; this.fax = fax; } public String getFirstName() { return firstName; } public void setFirstName(String firstName) { this.firstName = firstName; } public String getLastName() { return lastName; } public void setLastName(String lastName) { this.lastName = lastName; } public String getCompany() { return company; } public void setCompany(String company) { this.company = company; } public String getAddress() { return address; } public void setAddress(String address) { this.address = address; } public String getCity() { return city; } public void setCity(String city) { this.city = city; } public String getState() { return state; } public void setState(String state) { this.state = state; } public String getZip() { return zip; } public void setZip(String zip) { this.zip = zip; } public String getCounty() { return county; } public void setCounty(String county) { this.county = county; } public String getUrl() { return url; } public void setUrl(String url) { this.url = url; } public String getPhoneNumber() { return phoneNumber; } public void setPhoneNumber(String phoneNumber) { this.phoneNumber = phoneNumber; } public String getFax() { return fax; } public void setFax(String fax) { this.fax = fax; } } package com.examples.config; import javax.sql.DataSource; import org.apache.commons.dbcp2.BasicDataSource; import org.springframework.batch.core.configuration.annotation.EnableBatchProcessing; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.ComponentScan; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.PropertySource; import org.springframework.core.env.Environment; import org.springframework.core.io.ClassPathResource; import org.springframework.jdbc.datasource.init.DataSourceInitializer; import org.springframework.jdbc.datasource.init.ResourceDatabasePopulator; @Configuration @EnableBatchProcessing @ComponentScan("com.examples.*") @PropertySource("classpath:/com/examples/properties/batch.properties") public class SpringBatchConfiguration { @Autowired private Environment env; @Bean public DataSource dataSource() { BasicDataSource dataSource = new BasicDataSource(); dataSource.setUrl(env.getRequiredProperty("dataSource.url")); dataSource.setDriverClassName(env.getRequiredProperty("dataSource.driverClassName")); dataSource.setUsername(env.getRequiredProperty("dataSource.username")); dataSource.setPassword(env.getRequiredProperty("dataSource.password")); return dataSource; } @Bean public DataSourceInitializer h2DatabasePopulator() { ResourceDatabasePopulator populator = new ResourceDatabasePopulator(); populator.addScript( new ClassPathResource("org/springframework/batch/core/schema-h2.sql")); populator.addScript( new ClassPathResource("main/resource/sql/reset_user_registration.sql")); populator.setContinueOnError(true); populator.setIgnoreFailedDrops(true); DataSourceInitializer initializer = new DataSourceInitializer(); initializer.setDatabasePopulator(populator); initializer.setDataSource(dataSource()); return initializer; } } package com.examples; import org.springframework.batch.core.Job; import org.springframework.batch.core.JobExecution; import org.springframework.batch.core.JobParameters; import org.springframework.batch.core.configuration.JobRegistry; import org.springframework.batch.core.launch.JobLauncher; import org.springframework.batch.core.repository.JobRepository; import org.springframework.context.ApplicationContext; import org.springframework.context.annotation.AnnotationConfigApplicationContext; import com.examples.config.SpringBatchConfiguration; public class Main { public static void main(String[] args) throws Throwable { ApplicationContext context = new AnnotationConfigApplicationContext(SpringBatchConfiguration.class); JobRegistry jobRegistry = context.getBean("jobRegistry", JobRegistry.class); JobLauncher jobLauncher = context.getBean("jobLauncher", JobLauncher.class); JobRepository jobRepository = context.getBean("jobRepository", JobRepository.class); System.out.println(" jobRegistry: "+jobRegistry); System.out.println(" jobLauncher: "+jobLauncher); System.out.println(" jobRepository: "+jobRepository); Job job = context.getBean("insertIntoDbFromCsvJob", Job.class); JobExecution jobExecution = jobLauncher.run(job, new JobParameters()); } }
The registration.csv file has the following content:
In H2 database Console, you have to create the following table:
Now you have to run the Spring application and you can see the following information added into the BATCH.REGISTRATION table from the H2 database:
If you want, you can take a look at the following articles as well : SPRING BATCH: Sequential Steps, SPRING BATCH: Concurrent Steps.
Note: This article was inspired from the book named "Spring 5 Recipes: A problem-Solution Approach", Fourth Edition, written by Marten Deinum, Daniel Rubio and Josh Long. |
|
||
Copyright 2017-2021 © LEARN-IT-WITH-EXAMPLES.com All rights reserved. This website does not represent any corporation (Oracle, Microsoft, etc) in any way. This site is not using cookies, but it use some services that might use cookies. All information is supposed to be accurate, but it is not guaranteed to be correct. The usage of the information from this website is strictly at your own risk. If you don't like these policies, you have to stop using the website. |