Monday, 30 November 2020

JavaFX: Node: Attach data to a control

 

'javafx.scene.Node' class provides 'setUserData' method, it is used to associate some data to UI control, you can retrieve this data later point of time.

 

Syntax

public void setUserData(Object value)

 

Example

button1.setUserData(userData);

 

Let’s write simple program, that count button clicks.

 

ButtonClickCount.java

package com.sample.app.widgets;

import javafx.application.Application;
import javafx.geometry.Insets;
import javafx.geometry.Pos;
import javafx.scene.Scene;
import javafx.scene.control.Alert;
import javafx.scene.control.Button;
import javafx.scene.control.Label;
import javafx.scene.control.Alert.AlertType;
import javafx.scene.effect.DropShadow;
import javafx.scene.layout.HBox;
import javafx.scene.layout.VBox;
import javafx.scene.paint.Color;
import javafx.scene.text.Font;
import javafx.scene.text.FontPosture;
import javafx.stage.Stage;

public class ButtonClickCount extends Application {

    public static void main(String args[]) {
        launch(args);

    }

    @Override
    public void start(Stage primaryStage) throws Exception {

        HBox hBox1 = new HBox();
        Label label1 = new Label("Demo to count number of clicks");
        label1.setFont(Font.font("Verdana", FontPosture.REGULAR, 45));
        hBox1.getChildren().add(label1);
        hBox1.setPadding(new Insets(20, 20, 20, 20));

        Button button1 = new Button("Click Me");
        button1.setAlignment(Pos.CENTER);
        button1.setFont(Font.font("Verdana", FontPosture.REGULAR, 30));
        button1.setPadding(new Insets(10, 10, 10, 10));
        button1.setUserData(0);

        Button button2 = new Button("Click Count");
        button2.setAlignment(Pos.CENTER);
        button2.setFont(Font.font("Verdana", FontPosture.REGULAR, 30));
        button2.setPadding(new Insets(10, 10, 10, 10));

        HBox hBox2 = new HBox();
        hBox2.setSpacing(10);
        hBox2.setPadding(new Insets(20, 20, 20, 20));
        hBox2.getChildren().addAll(button1, button2);

        button1.setOnAction((event) -> {
            Integer userData = (Integer) button1.getUserData();
            userData += 1;

            button1.setUserData(userData);

        });

        button2.setOnAction((event) -> {
            Integer userData = (Integer) button1.getUserData();

            Alert alert = new Alert(AlertType.INFORMATION);
            alert.setTitle("Count Checker");
            alert.setContentText("You clicked " + userData + " times");

            alert.showAndWait();

        });

        DropShadow dropShadow = new DropShadow();
        dropShadow.setOffsetX(5);
        dropShadow.setOffsetY(5);
        dropShadow.setColor(Color.GRAY);

        VBox vBox = new VBox();
        vBox.getChildren().addAll(hBox1, hBox2);
        vBox.setEffect(dropShadow);

        Scene scene = new Scene(vBox, 900, 500, Color.WHITE);

        primaryStage.setTitle("Button Demo 1");
        primaryStage.setScene(scene);
        primaryStage.show();
    }

}

 

Output

 

 


Click the button ‘Click Me’ n number of times, and click on ‘Click Count’ button to see how many times you clicked.



 

Previous                                                    Next                                                    Home

Spring Batch: Maintain State while reading

 

In this post, I am going to show how to maintain state while reading the data.

 

ItemStream Interface

ItemStream interface provide access to the ExecutionContext, where the state is maintained.

 

Following table summarizes the methods defined by ItemStream interface.

 

Method

Description

open(ExecutionContext executionContext)

Open the stream for the provided ExecutionContext. When the job is executed first time, then new ExecutionContext object gets created and given to open method.

 

But when the job is restarted, then already persisted ExecutionContext object is given to open method. Using the persisted ExecutionContext we can restart the job where we left.

void update(ExecutionContext executionContext)

Indicates that the execution context provided during open is about to be saved. If any state is remaining, but has not been put in the context, it should be added here.

 

This method is called once per chunk or once per transaction. We can use this method to update the current state.

void close()

If any resources are needed for the stream to operate they need to be destroyed here. Once this method has been called all other methods (except open) may throw an exception.

 

 


 

As shown in above figure, When a job started execution, open method of ItemReader gets called. When the job is executed first time, then new ExecutionContext object gets created and given to open method. But when the job is restarted, then already persisted ExecutionContext object is given to open method. Using the persisted ExecutionContext we can restart the job where we left

 

‘update’ method is called once per chunk or once per transaction (after read -> Process -> Write). We can use this method to update the current state.

 

‘close’ method is called once per chunk or once per transaction. If any resources are needed for the stream to operate they need to be destroyed here.

 

How to create stateful reader?

By implementing 'ItemStreamReader' interface you can create stateful item reader.

 

public class MyStatefulItemReader implements ItemStreamReader<String> {

         ......

         ......

}

 

Find the below working application.

 

Step 1: Create new maven project 'stateful-read-demo'.

 

Step 2: Update pom.xml with maven dependencies.

 

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/xsd/maven-4.0.0.xsd">
	<modelVersion>4.0.0</modelVersion>
	<groupId>com.sample.app</groupId>
	<artifactId>stateful-read-demo</artifactId>
	<version>1</version>

	<parent>
		<groupId>org.springframework.boot</groupId>
		<artifactId>spring-boot-starter-parent</artifactId>
		<version>2.1.6.RELEASE</version>
	</parent>

	<properties>
		<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
	</properties>

	<dependencies>

		<!-- https://mvnrepository.com/artifact/org.springframework.batch/spring-batch-core -->
		<dependency>
			<groupId>org.springframework.batch</groupId>
			<artifactId>spring-batch-core</artifactId>
		</dependency>

		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-web</artifactId>
		</dependency>

		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-data-jpa</artifactId>
		</dependency>

		<dependency>
			<groupId>com.h2database</groupId>
			<artifactId>h2</artifactId>
		</dependency>
	</dependencies>
</project>


Step 3: Create new package ‘com.sample.app.readers’ and define MyStatefulItemReader.

 

MyStatefulItemReader.java

package com.sample.app.readers;

import java.util.List;

import org.springframework.batch.item.ExecutionContext;
import org.springframework.batch.item.ItemStreamException;
import org.springframework.batch.item.ItemStreamReader;
import org.springframework.batch.item.NonTransientResourceException;
import org.springframework.batch.item.ParseException;
import org.springframework.batch.item.UnexpectedInputException;

public class MyStatefulItemReader implements ItemStreamReader<String> {

	private List<String> items;
	private int currentIndex;
	private boolean firstRun;

	public MyStatefulItemReader(List<String> items) {
		this.items = items;
		currentIndex = 0;
		firstRun = true;
	}

	@Override
	public void open(ExecutionContext executionContext) throws ItemStreamException {
		System.out.println("In open method");
		if (executionContext.containsKey("currentItemIndex")) {
			this.currentIndex = executionContext.getInt("currentItemIndex");
			this.firstRun = false;
		} else {
			this.currentIndex = 0;
			executionContext.put("currentItemIndex", this.currentIndex);
		}

	}

	@Override
	public void update(ExecutionContext executionContext) throws ItemStreamException {
		System.out.println("In update method");
		executionContext.put("currentItemIndex", this.currentIndex);
	}

	@Override
	public void close() throws ItemStreamException {
		System.out.println("In close method");

	}

	@Override
	public String read() throws Exception, UnexpectedInputException, ParseException, NonTransientResourceException {
		System.out.println("In read method");
		String item = null;

		if (currentIndex == 9 && firstRun) {
			throw new RuntimeException("Error Occuured while processing the data");
		}

		if (currentIndex < items.size()) {
			item = items.get(currentIndex);
			currentIndex++;
		}

		return item;
	}

}


As you see ‘read’ method, I am throwing exception for the item 9.

 

As you see ‘open’ method, I am reading ‘currentItemIndex’ value from ExecutionContext on restart of the application.

 

Step 4: Create package ‘com.sample.app.configuration’ and define JobConfiguration.

 

JobConfiguration.java

package com.sample.app.configuration;

import java.util.ArrayList;
import java.util.List;

import org.springframework.batch.core.Job;
import org.springframework.batch.core.Step;
import org.springframework.batch.core.configuration.annotation.EnableBatchProcessing;
import org.springframework.batch.core.configuration.annotation.JobBuilderFactory;
import org.springframework.batch.core.configuration.annotation.StepBuilderFactory;
import org.springframework.batch.core.repository.JobRepository;
import org.springframework.batch.item.ItemWriter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.transaction.PlatformTransactionManager;

import com.sample.app.readers.MyStatefulItemReader;

@Configuration
@EnableBatchProcessing
public class JobConfiguration {
	@Autowired
	private JobBuilderFactory jobBuilderFactory;

	@Autowired
	private StepBuilderFactory stepBuilderFactory;

	@Bean
	public MyStatefulItemReader myStatefulItemReader() {
		List<String> items = new ArrayList<>();

		for (int i = 0; i < 25; i++) {
			items.add("Item " + i);
		}

		return new MyStatefulItemReader(items);
	}

	@Bean
	public ItemWriter itemWriter() {
		return new ItemWriter<String>() {

			@Override
			public void write(List<? extends String> items) throws Exception {
				for (String item : items) {
					System.out.println("Writing : " + item);
				}
			}

		};
	}

	@Bean
	public Step step1() {
		return this.stepBuilderFactory.get("step1").chunk(5).reader(myStatefulItemReader()).writer(itemWriter())
				.build();
	}

	@Bean
	public Job myJob(JobRepository jobRepository, PlatformTransactionManager platformTransactionManager) {

		return jobBuilderFactory.get("My-First-Job").start(step1()).build();
	}

}


Step 5: Define App.java

 

App.java 

package com.sample.app;

import org.springframework.batch.core.configuration.annotation.EnableBatchProcessing;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@EnableBatchProcessing
@SpringBootApplication
public class App {

	public static void main(String[] args) {
		SpringApplication.run(App.class, args);
	}
}

 

Step 6: Create ‘application.properties’ file under src/main/resources folder.

 

application.properties

 

logging.level.root=ERROR
logging.level.org.hibernate=ERROR

## H2 specific properties
spring.h2.console.enabled=true
spring.h2.console.path=/h2

spring.datasource.url=jdbc:h2:file:~/db/myOrg.db;DB_CLOSE_ON_EXIT=FALSE;DB_CLOSE_DELAY=-1;

spring.datasource.username=krishna
spring.datasource.password=password123

spring.datasource.driverClassName=org.h2.Driver

## JPA specific properties
# Creates the schema, destroying previous data.
spring.jpa.hibernate.ddl-auto=create-drop

spring.jpa.database-platform=org.hibernate.dialect.H2Dialect

spring.jpa.show-sql=false
spring.jpa.properties.hibernate.format_sql=false

## Database connection pooling properties
# Number of ms to wait before throwing an exception if no connection is available.
spring.datasource.max-wait=10000

# Maximum number of active connections that can be allocated from this pool at the same time.
spring.datasource.tomcat.max-active=10
spring.datasource.tomcat.max-idle=5
spring.datasource.tomcat.min-idle=3

 

Total project structure looks like below.

 


Run App.java, you will see below messages in console.

In open method
In update method
In read method
In read method
In read method
In read method
In read method
Writing : Item 0
Writing : Item 1
Writing : Item 2
Writing : Item 3
Writing : Item 4
In update method
In read method
In read method
In read method
In read method
In read method
2020-04-07 15:45:09.774 ERROR 70982 --- [           main] o.s.batch.core.step.AbstractStep         : Encountered an error executing step step1 in job My-First-Job

java.lang.RuntimeException: Error Occuured while processing the data
	at com.sample.app.readers.MyStatefulItemReader.read(MyStatefulItemReader.java:55) ~[classes/:na]
	at com.sample.app.readers.MyStatefulItemReader.read(MyStatefulItemReader.java:1) ~[classes/:na]
	at org.springframework.batch.core.step.item.SimpleChunkProvider.doRead(SimpleChunkProvider.java:94) ~[spring-batch-core-4.1.2.RELEASE.jar:4.1.2.RELEASE]
	.....
	.....
In close method

Open the url 'http://localhost:8080/h2' to see h2 console.

 

 

Give the username as 'krishna' and password as 'password123' and login to H2 console.



See the data of 'BATCH_STEP_EXECUTION_CONTEXT' table.

 


 

Take the information from 'SHORT_CONTEXT', you will see following information.

{
	"batch.taskletType": "org.springframework.batch.core.step.item.ChunkOrientedTasklet",
	"batch.stepType": "org.springframework.batch.core.step.tasklet.TaskletStep",
	"currentItemIndex": 5
}


As you see above json, currentItemIndex value is set to 5. That means we processed items till the index 4 and when we restart the application, we should start processing from the index 5.

 

Stop and restart the application, you will see below messages in console.

In open method
In update method
In read method
In read method
In read method
In read method
In read method
Writing : Item 5
Writing : Item 6
Writing : Item 7
Writing : Item 8
Writing : Item 9
In update method
In read method
In read method
In read method
In read method
In read method
Writing : Item 10
Writing : Item 11
Writing : Item 12
Writing : Item 13
Writing : Item 14
In update method
In read method
In read method
In read method
In read method
In read method
Writing : Item 15
Writing : Item 16
Writing : Item 17
Writing : Item 18
Writing : Item 19
In update method
In read method
In read method
In read method
In read method
In read method
Writing : Item 20
Writing : Item 21
Writing : Item 22
Writing : Item 23
Writing : Item 24
In update method
In read method
In update method
In close method


You can download complete working application from this link.

https://github.com/harikrishna553/springboot/tree/master/batch/stateful-read-demo

 



 







Previous                                                    Next                                                    Home

Spring Batch: JdbcPagingItemReader: Read data from table

In this post, I am going to explain how to read data from a table using JdbcPagingItemReader.

 

Step 1: Define RowMapper that maps ResultSet to an Employee instance.

public class EmployeeRowMapper implements RowMapper<Employee> {

	@Override
	public Employee mapRow(ResultSet rs, int rowNum) throws SQLException {

		Employee emp = new Employee();

		emp.setId(rs.getInt("id"));
		emp.setFirstName(rs.getString("first_name"));
		emp.setLastName(rs.getString("last_name"));

		return emp;
	}

}

 

Step 2: Define JdbcPagingItemReader bean.

@Bean
public JdbcPagingItemReader<Employee> jdbcPagingItemReader() {
	JdbcPagingItemReader<Employee> pagingItemReader = new JdbcPagingItemReader<>();

	pagingItemReader.setDataSource(dataSource);
	pagingItemReader.setFetchSize(3);
	pagingItemReader.setRowMapper(new EmployeeRowMapper());

	MySqlPagingQueryProvider mySqlPagingQueryProvider = new MySqlPagingQueryProvider();
	mySqlPagingQueryProvider.setSelectClause("id, first_name, last_name");
	mySqlPagingQueryProvider.setFromClause("FROM employee");

	Map<String, Order> orderByKeys = new HashMap<>();
	orderByKeys.put("first_name", Order.ASCENDING);

	mySqlPagingQueryProvider.setSortKeys(orderByKeys);

	pagingItemReader.setQueryProvider(mySqlPagingQueryProvider);

	return pagingItemReader;
}

 

As you see we set the query to execute and EmployeeRowMapper to the reader.

 

Step 3: Define ItemWriter that writes the chunk to console.

@Bean
public ItemWriter<? super Object> itemWriter() {
	return emps -> {
		System.out.println("\nWriting chunk to console");
		for (Object emp : emps) {
			System.out.println(emp);
		}
	};
}

 

Step 4: Define step with reader and writer.

@Bean
public Step step1() {
	return this.stepBuilderFactory.get("step1").chunk(3).reader(jdbcPagingItemReader()).writer(itemWriter()).build();
}

Step 5: Define job.

@Bean
public Job myJob(JobRepository jobRepository, PlatformTransactionManager platformTransactionManager) {
	return jobBuilderFactory.get("My-First-Job").start(step1()).build();
}

 

That’s it you are done.

 

Find the below working application.

 

Step 1: Create new maven project ‘jdbcCursorItemReader-demo’.

 

Step 2: Update pom.xml with maven dependencies.

 

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/xsd/maven-4.0.0.xsd">
	<modelVersion>4.0.0</modelVersion>
	<groupId>com.sample.app</groupId>
	<artifactId>jdbcPagingItemReader-demo</artifactId>
	<version>1</version>

	<parent>
		<groupId>org.springframework.boot</groupId>
		<artifactId>spring-boot-starter-parent</artifactId>
		<version>2.1.6.RELEASE</version>
	</parent>

	<properties>
		<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
	</properties>

	<dependencies>

		<!-- https://mvnrepository.com/artifact/org.springframework.batch/spring-batch-core -->
		<dependency>
			<groupId>org.springframework.batch</groupId>
			<artifactId>spring-batch-core</artifactId>
		</dependency>

		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-web</artifactId>
		</dependency>

		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-data-jpa</artifactId>
		</dependency>

		<dependency>
			<groupId>com.h2database</groupId>
			<artifactId>h2</artifactId>
		</dependency>
	</dependencies>
</project>

 

Step 3: Create application.properties file under src/main/resources folder.

 

application.properties

 

logging.level.root=ERROR
logging.level.org.hibernate=ERROR

## H2 specific properties
spring.h2.console.enabled=true
spring.h2.console.path=/h2

spring.datasource.url=jdbc:h2:file:~/db/myOrg.db;DB_CLOSE_ON_EXIT=FALSE;DB_CLOSE_DELAY=-1;

spring.datasource.username=krishna
spring.datasource.password=password123

spring.datasource.driverClassName=org.h2.Driver

## JPA specific properties
# Creates the schema, destroying previous data.
spring.jpa.hibernate.ddl-auto=create-drop

spring.jpa.database-platform=org.hibernate.dialect.H2Dialect

spring.jpa.show-sql=false
spring.jpa.properties.hibernate.format_sql=false

## Database connection pooling properties
# Number of ms to wait before throwing an exception if no connection is available.
spring.datasource.max-wait=10000

# Maximum number of active connections that can be allocated from this pool at the same time.
spring.datasource.tomcat.max-active=10
spring.datasource.tomcat.max-idle=5
spring.datasource.tomcat.min-idle=3

 

Step 4: Create data.sql file in src/main/resources folder. It is used to insert data to employee table.

 

data.sql

 

INSERT INTO employee (id, first_name, last_name) VALUES
  (1, 'Sowmya', 'Krishna'),
  (2, 'Mridhu', 'Latha'),
  (3, 'Gowthami','Prasad'),
  (4, 'Sailu', 'Venkat'),
  (5, 'Chamu', 'Krishna'),
  (6, 'Rama', 'Lakshman'),
  (7, 'Saranya', 'Nataraj'),
  (8, 'Suneetha', 'Surendra');

 

Step 5: Create package ‘com.sample.app.entity’ and define Employee class.

 

Employee.java

 

package com.sample.app.entity;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.Table;

@Entity
@Table(name = "employee")
public class Employee {

	@Id
	@GeneratedValue
	@Column(name = "id")
	private int id;

	@Column(name = "first_name")
	private String firstName;

	@Column(name = "last_name")
	private String lastName;

	public int getId() {
		return id;
	}

	public void setId(int id) {
		this.id = id;
	}

	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;
	}

	@Override
	public String toString() {
		StringBuilder builder = new StringBuilder();
		builder.append("Employee [id=").append(id).append(", firstName=").append(firstName).append(", lastName=")
				.append(lastName).append("]");
		return builder.toString();
	}

}

 

Step 6: Create package ‘com.smaple.app.mappers’ and define EmployeeRowMapper.

 

EmployeeRowMapper.java

 

package com.smaple.app.mappers;

import java.sql.ResultSet;
import java.sql.SQLException;

import org.springframework.jdbc.core.RowMapper;

import com.sample.app.entity.Employee;

public class EmployeeRowMapper implements RowMapper<Employee> {

	@Override
	public Employee mapRow(ResultSet rs, int rowNum) throws SQLException {

		Employee emp = new Employee();

		emp.setId(rs.getInt("id"));
		emp.setFirstName(rs.getString("first_name"));
		emp.setLastName(rs.getString("last_name"));

		return emp;
	}

}

 

Step 7: Create package ‘com.sample.app.configuration’ and define JobConfiguration.

 

JobConfiguration.java

 

package com.sample.app.configuration;

import java.util.HashMap;
import java.util.Map;

import javax.sql.DataSource;

import org.springframework.batch.core.Job;
import org.springframework.batch.core.Step;
import org.springframework.batch.core.configuration.annotation.EnableBatchProcessing;
import org.springframework.batch.core.configuration.annotation.JobBuilderFactory;
import org.springframework.batch.core.configuration.annotation.StepBuilderFactory;
import org.springframework.batch.core.repository.JobRepository;
import org.springframework.batch.item.ItemWriter;
import org.springframework.batch.item.database.JdbcPagingItemReader;
import org.springframework.batch.item.database.Order;
import org.springframework.batch.item.database.support.MySqlPagingQueryProvider;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.transaction.PlatformTransactionManager;

import com.sample.app.entity.Employee;
import com.smaple.app.mappers.EmployeeRowMapper;

@Configuration
@EnableBatchProcessing
public class JobConfiguration {
	@Autowired
	private JobBuilderFactory jobBuilderFactory;

	@Autowired
	private StepBuilderFactory stepBuilderFactory;

	@Autowired
	private DataSource dataSource;

	@Bean
	public JdbcPagingItemReader<Employee> jdbcPagingItemReader() {
		JdbcPagingItemReader<Employee> pagingItemReader = new JdbcPagingItemReader<>();

		pagingItemReader.setDataSource(dataSource);
		pagingItemReader.setFetchSize(3);
		pagingItemReader.setRowMapper(new EmployeeRowMapper());

		MySqlPagingQueryProvider mySqlPagingQueryProvider = new MySqlPagingQueryProvider();
		mySqlPagingQueryProvider.setSelectClause("id, first_name, last_name");
		mySqlPagingQueryProvider.setFromClause("FROM employee");

		Map<String, Order> orderByKeys = new HashMap<>();
		orderByKeys.put("first_name", Order.ASCENDING);

		mySqlPagingQueryProvider.setSortKeys(orderByKeys);

		pagingItemReader.setQueryProvider(mySqlPagingQueryProvider);

		return pagingItemReader;
	}

	@Bean
	public ItemWriter<? super Object> itemWriter() {
		return emps -> {
			System.out.println("\nWriting chunk to console");
			for (Object emp : emps) {
				System.out.println(emp);
			}
		};
	}

	@Bean
	public Step step1() {
		return this.stepBuilderFactory.get("step1").chunk(3).reader(jdbcPagingItemReader()).writer(itemWriter())
				.build();
	}

	@Bean
	public Job myJob(JobRepository jobRepository, PlatformTransactionManager platformTransactionManager) {

		return jobBuilderFactory.get("My-First-Job").start(step1()).build();
	}

}

 

Step 8: Define App.java

 

App.java

 

package com.sample.app;

import org.springframework.batch.core.configuration.annotation.EnableBatchProcessing;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@EnableBatchProcessing
@SpringBootApplication
public class App {

	public static void main(String[] args) {
		SpringApplication.run(App.class, args);
	}
}

  Total project structure looks like below.

 


Run App.java, you will see below messages in console.

Writing chunk to console
Employee [id=5, firstName=Chamu, lastName=Krishna]
Employee [id=3, firstName=Gowthami, lastName=Prasad]
Employee [id=2, firstName=Mridhu, lastName=Latha]

Writing chunk to console
Employee [id=6, firstName=Rama, lastName=Lakshman]
Employee [id=4, firstName=Sailu, lastName=Venkat]
Employee [id=7, firstName=Saranya, lastName=Nataraj]

Writing chunk to console
Employee [id=1, firstName=Sowmya, lastName=Krishna]
Employee [id=8, firstName=Suneetha, lastName=Surendra]

 

You can download the application from this link.

https://github.com/harikrishna553/springboot/tree/master/batch/jdbcPagingItemReader-demo

 

 

 

 

Previous                                                    Next                                                    Home