Spring Batch : PassThroughFieldExtractor with BigDecimal formatting

前端 未结 1 540
无人共我
无人共我 2021-01-26 11:43

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,
         


        
相关标签:
1条回答
  • 2021-01-26 12:30

    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);
      }
    }
    
    0 讨论(0)
提交回复
热议问题