Java Reference
In-Depth Information
regardless of what the object looks like. However, the ItemProcessor is where the business logic of your
process exists. Because of this, you will virtually always need to create custom implementations of them.
In this section, you will look at how to create a custom ItemProcessor implementation that filters certain
items that were read from begin written.
Filtering Items
In the previous section, you created two of your own ItemProcessors: a CustomerItemProcessor that
updated the item it received with the corresponding database ID and the
AccountExecutiveItemProcessor that associates the customer's AccountExecutive with the Customer item
so that information about the customer and the account executive can be written in the output file.
However, you didn't do a good job with error handling in the previous example. What happens if
the Customer is not found and the ID is not updated in the CustomerItemProcessor? In this scenario,
you probably want to filter the item out so the job does not try the account executive lookup. So how do
you tell Spring Batch not to process the item anymore?
Spring Batch has you covered. It is actually very easy to tell Spring Batch not to continue processing
an item. To do so, instead of the ItemProcessor returning an item, it returns null. So in this case, if you
can't find a customer in your database, you will want the CustomerItemProcessor to return null so that
the AccountExecutiveItemProcessor doesn't throw an exception by not having a Customer to look up by.
The updated code for this is shown in Listing 8-23.
Listing 8-23. CustomerItemProcessor that Handles Nonexistent Customers
package com.apress.springbatch.chapter8;
import org.springframework.batch.item.ItemProcessor;
public class CustomerItemProcessor implements ItemProcessor<Customer, Customer> {
private CustomerDao customerDao;
public Customer process(Customer customer) {
Customer currentCustomer =
customerDao.getCustomerByNameAndZip(customer.getFirstName(),
customer.getLastName(),
customer.getZip());
if(currentCustomer != null) {
customer.setId(currentCustomer.getId());
return customer;
} else {
return null;
}
}
public void setCustomerDao(CustomerDao customerDao) {
this.customerDao = customerDao;
}
}
With just this small change to your job, you can now run it without fear that the
AccountExecutiveItemProcessor will fail because it doesn't have a customer number to look up. If you
 
Search WWH ::




Custom Search