NullPointerException
NullPointerException

Reputation: 3814

How to add column alias names to output csv file spring batch

I need to add the aliases defined in the SQL query while generating the CSV file.

I see some example using FlatFileHeaderCallback but there I don't have a way to pass the aliases

is there any way to get the column aliases in write(List<? extends T> items) method of FlatFileItemWriter

Upvotes: 1

Views: 3237

Answers (2)

Navin
Navin

Reputation: 7

Create a custom class(assuming 5 csv columns):

public class MyFlatFileWriter implements FlatFileHeaderCallback {

 @Override
 public void writeHeader(Writer writer) throws IOException {
    writer.write("Col1,Col2,Col3,Col4,Col5");
}
}

Add bean & its reference in writer bean:

    <bean id="flatFileWriter" class="org.springframework.batch.item.file.FlatFileItemWriter">
      <property name="resource" value="file:csv/outputs/name.csv" />
      <property name="headerCallback" ref="headerCallback" />
      <property name="lineAggregator">
       ............
      </property>
    </bean>

<bean id="headerCallback" class="com.whatever.model.MyFlatFileWriter" />

Upvotes: 1

Thrax
Thrax

Reputation: 1964

For starters, I think you could simply use a custom FlatFileHeaderCallback which takes a String as a parameter and writes it :

public class CustomHeaderWriter implements FlatFileHeaderCallback {

    private String header;

    @Override
    public void writeHeader(Writer writer) throws IOException {
        writer.write(header);
    }

    public void setHeader(String header) {
        this.header = header;
    }
}

To use it, declare it in your FlatFileItemWriter and give it a String that contains the name of your columns/aliases separated by your flat file delimiter :

<bean class="org.springframework.batch.item.file.FlatFileItemWriter" scope="step">
   <property name="headerCallback">
       <bean class="xx.xx.xx.CustomHeaderWriter">
           <property name="header" value="${columns.or.aliases}"></property>
        </bean>
   </property>
</bean>

Now, I suppose you don't want to write the columns/aliases a second time for the header, and would like to "extract" them from the SQL query. This could be accomplished for example by fiddling with the CustomHeaderWriter :

  • Instead of passing the columns/aliases directly, you could give it the actual SQL query
  • Using a Regular Expression or manual parsing, you could then extract the aliases or the columns names (strings beween SELECT and FROM, split with ,, strip quotes, etc.)
  • You would then need to pass (or use a constant) the delimiter of the FlatFileItemWriter
  • Finally, write the String you just built

Upvotes: 3

Related Questions