1

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

2 Answers 2

3

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
Sign up to request clarification or add additional context in comments.

1 Comment

nice and clean solution!
1

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" />

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.