OpenCSV Date Analysis

We use OpenCSV to analyze the CSV file and bind its values ​​directly to the model object (OpenJPA bean object) using the CsvToBean class.

However, the problem is that in CSV there are some values ​​that are (obviously) parsed as Strings , but must be set in the Date property, so basically the CsvToBean class dies when trying to dynamically call the write method (i.e. it tries to set the property Date with raw String value).

Is there any object inside OpenCSV that will allow me to indicate which type each column should be mapped to? If not, do you have any suggestions on which class should be extended / redefined in order to facilitate this? Inspecting other available strageties in the OpenCSV distribution in the directory /test/au/com/bytecode/opencsv/bean/ did not bring me to a conclusion.

I think that I could play with the Date property installer and make it a universal method that would pass the type passed as an argument and try to parse the passed value into Date , if it is not Date already, but ... we use Entity annotated entities , and I don’t want to see later that this setter hack shot us in the leg because the OpenJPA Enhancer suddenly did not like the generic setter.

I tricked myself around this issue a couple of times - I could probably solve this problem by using reflection and writing my own bean logic, but I hate reinventing the wheel and having the feeling / hope that this can be done somewhat easily within the existing OpenCSV framework.

If necessary, I can publish some code, but there really isn’t much there.

Any thoughts? thanks.

+6
source share
3 answers

How to create a copy of Date property in class definition? We did something similar using BeanUtils

So your Bean class contains

 String dateString; Date date; public void setDateString(String dateString) { // This method can parse the dateString and set date object as well } public void setDate(Date date) { // Use this for JPA } 
+3
source

Maybe you will use the cue method next to the original:

 @Transient public void setDate(String date) { Date d = parseDate(date); setDate(d); } @Column public void setDate(Date date) { this.date = date; } 
+1
source

Alternatively, you can use Super CSV , which has an API cell processor that allows you to read the bean (no change) using ParseDate for this column.

+1
source

Source: https://habr.com/ru/post/887017/


All Articles