質問

I'm using Spring Batch to extract a CSV file from a DB table which has a mix of column types. The sample table SQL schema is

[product] [varchar](16) NOT NULL,
[version] [varchar](16) NOT NULL,
[life_1_dob] [date] NOT NULL,
[first_itm_ratio] [decimal](9,6) NOT NULL,

the sample Database column value for the 'first_itm_ration' field are

first_itm_ratio
1.050750
0.920000

but I would like my CSV to drop the trailing zero's from values.

first_itm_ratio
1.05075
0.92

I'd prefer not to have to define the formatting for each specific field in the table, but rather have a global object specific formatting for all columns of that data type.

My csvFileWriter bean

<bean id="csvFileWriter"      class="org.springframework.batch.item.file.FlatFileItemWriter" scope="step">
    <property name="resource" ref="fileResource"/>
    <property name="lineAggregator">
        <bean class="org.springframework.batch.item.file.transform.DelimitedLineAggregator">
            <property name="delimiter">
                <util:constant static-field="org.springframework.batch.item.file.transform.DelimitedLineTokenizer.DELIMITER_COMMA"/>
            </property>
            <property name="fieldExtractor">
                <bean class="org.springframework.batch.item.file.transform.PassThroughFieldExtractor" />
            </property>
        </bean>
    </property>
</bean>
役に立ちましたか?

解決

You can

  1. Write your own BigDecimalToStringConverter implements Converter<BigDecimal, String> to format big decimal without trailing 0's
  2. Create a new ConversionService (MyConversionService) and register into the custom converter
  3. Extends DelimitedLineAggregator, inject MyConversionService, override doAggregate() to format fields using injected conversion service

public class MyConversionService extends DefaultConversionService {
  public MyConversionService() {
    super();
    addConverter(new BigDecimalToStringConverter());
  }
}

public class MyFieldLineAggregator<T> extends DelimitedLineAggregator<T> {
  private ConversionService cs = new MyConversionService();

  public String doAggregate(Object[] fields) {
    for(int i = 0;i < fields.length;i++) {
      final Object o = fields[i];
      if(cs.canConvert(o.getClass(), String.class)) {
        fields[i] = cs.convert(o, String.class);
      }
    }
    return super.doAggregate(fields);
  }
}
ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top