concept Product in category spring

appears as: Product, Product
Spring Batch in Action

This is an excerpt from Manning's book Spring Batch in Action.

You may recognize this as the classic comma-separated value (CSV) format. There’s nothing out of the ordinary in this flat file: for a given row, the format separates each column value from the next with a comma. Spring Batch maps each row in the flat file to a Product domain object.

Using the JsonLineMapper class is convenient to get data as Map objects, but it’s perhaps not exactly what you need. At this point in the case study, you want to support several input data formats homogenously. For every type of format, data must come through as Product instances.

For this reason, your work isn’t finished. You need to create an additional class implementing the LineMapper interface to wrap a JsonLineMapper. The purpose of this class, called WrappedJsonLineMapper, is to delegate processing to the target JsonLineMapper instance and then to create Product instances from Map objects. The following listing shows the JsonLineMapperWrapper class.

Listing 5.6. A JsonLineMapper wrapper to create data objects

The WrappedJsonLineMapper class is a wrapper for a target JsonLineMapper instance defined with the delegate property. This makes it possible to delegate processing within the mapLine method and to get the corresponding result as a Map. The mapLine method then converts the Map to a Product object .

Listing 5.2. The Product bean
public class Product { private String id; private String name; private String description; price float price; public String getId() { return id; } public void setId(String id) { this.id = id; } (...) public float getPrice() { return price; } public void setPrice(float price) { this. price = price; } }

To map the FieldSet instance to the Product data bean, you implement a FieldSetMapper to populate Product instances from a FieldSet instance. The following listing shows the FieldSetMapper implementation that creates Product instances.

Listing 5.3. Custom FieldSetMapper for creating Product objects
public class ProductFieldSetMapper implements FieldSetMapper<Product> { public Product mapFieldSet(FieldSet fieldSet) { Product product = new Product(); product.setId(fieldSet.readString("id")); product.setName(fieldSet.readString("name")); product.setDescription(fieldSet.readString("description")); product.setPrice(fieldSet.readFloat("price")); return product; } }

In the mapFieldSet method implementation, an uninitialized instance of a Product is first created. The mapFieldSet method then uses the FieldSet instance and its various read methods. The FieldSet class provides multiple read methods, one for each primitive Java type, plus String, Date, and BigDecimal. Each read method takes a field name or field index as a parameter; some methods also provide an argument for a default value.