Format ResultSet to specific DecimalFormat in Univocity Parser

316 views Asked by At

In my project I've been using Univocity-parsers to convert SQL queries into CSV files. It used to first map the queries to Java Beans and then used CsvRoutines to write the CSV.

public static class Bean {
    @Parsed(field = "double_value")
    public Double doubleValue;

    public Bean(Double doubleValue) {
        this.doubleValue = doubleValue;
    }
}

@Test
public void writeToCsv() {
    List<Bean> beans = List.of(new Bean(10.0), new Bean(50.5), new Bean(12.0));
    CsvRoutines csvRoutines = new CsvRoutines();
    StringWriter stringWriter = new StringWriter();
    csvRoutines.writeAll(beans, Bean.class, stringWriter);
    System.out.println(stringWriter);
}

This gives the following result:

10.0
50.5
12.0

Now I'm refactoring for a more generic approach to dump the ResultSet directly into the CsvRoutines. Similar to the example above, I made a small table in Postgres:

create table bean(
    double_value numeric
);
insert into bean values (10), (50.5), (12);

@Test
public void writeToCsv() throws SQLException {
    Connection c = createJdbcConnection();
    PreparedStatement stmt = c.prepareStatement("select double_value from bean");
    ResultSet rs = stmt.executeQuery();

    CsvRoutines csvRoutines = createCsvRoutines();
    StringWriter stringWriter = new StringWriter();
    csvRoutines.write(rs, stringWriter);
    System.out.println(stringWriter);
}

Now, the result doesn't always include the decimal numbers.

10
50.5
12

I'd like it to produce the exact same output as in the initial version for compatibility reasons. I've tried configuring a custom ObjectRowWriterProcessor, but it doesn't seem to format it correctly.

private CsvRoutines createCsvRoutines() {
    CsvWriterSettings writerSettings = new CsvWriterSettings();
    ObjectRowWriterProcessor rowProcessor = new ObjectRowWriterProcessor();
    rowProcessor.convertType(Double.class, Conversions.formatToNumber("0.0"));
    writerSettings.setRowWriterProcessor(rowProcessor);
    return new CsvRoutines(writerSettings);
}

How can I configure the CsvRoutines to always write in the 0.0 format like initially?

1

There are 1 answers

0
Jaims On BEST ANSWER

Looks like the ObjectRowWriterProcessor approach works fine, but the type at runtime is BigDecimal instead of a Double.

So changing the following line does produce the desired result:

rowProcessor.convertType(BigDecimal.class, Conversions.formatToNumber("0.0"));