S
S
SaF982020-03-17 23:06:03
Java
SaF98, 2020-03-17 23:06:03

How to implement composition in OpenCSV?

Hello, there are two bins:

public class Person {
    private long id;
    private String name;
// getter setter
}
public class Job {
    private long id;
    private Person person;
// getter setter
}


The documentation provides an example in which a nested bean is represented as a list:

public class Person {
    @CsvBindByPosition(position = 0)
    private long id;
    @CsvBindByPosition(position = 1)
    private String name;
// getter setter
}
public class Job {
    @CsvBindByPosition(position = 0)
    private long id;
    @CsvBindAndSplitByPosition(position = 1, converter = TextToPerson.class, elementType = Person.class)
    private List<Person> person;
// getter setter
}


class converter
public class TextToPerson extends AbstractCsvConverter {

    @Override
    public Object convertToRead(String s) throws CsvDataTypeMismatchException, CsvConstraintViolationException {
        Person person = new Person();
        DataProviderCSV csv = new DataProviderCSV();
        csv.getPersonById(Long.parseLong(s)).forEach(p->{
            person.setId(p.getId());
            person.setName(p.getName());
        });
        return person;
    }
    @Override
    public String convertToWrite(Object value) throws CsvDataTypeMismatchException {
        Person person = (Person) value;
        return String.valueOf(person.getId());
    }
}


The idea is that when writing, id was written as a nested bean, and when reading, data was taken from another table.
At the same time, convertToWrite works, but:
1) ConvertToRead() does not work, for reading I use CsvToBeanBuilder().withType(clazz)?
2) How can a Person be used instead of a List in a Job bean?

Answer the question

In order to leave comments, you need to log in

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question